У меня небольшая проблема с моим кодом для связанного списка, использующего базовую структуру, называемую element.
Сама программа довольно проста: введите текстовый файл и выведите каждое отдельное слово вместе с тем, сколько раз слово встречается.
У меня выход работает точно так, как я хочу.
Но у меня возникают проблемы с удалением всей выделенной памяти в конце моей программы.
Вэлгринд говорит мне, что 1 блок из 48 байт все еще занят, и проблема имеет какое-то отношение к строке 39: **temp = new element;**
, но я все еще не знаю, не удаляю ли я первый илипоследний элемент или где я должен это сделать.
Есть идеи?
std::string fileName;
element * head = nullptr;
element * temp = nullptr;
// Input fileName to be read into file stream
std::cout << "Input a file name to count the frequency of each word used: ";
std::cin >> fileName;
std::ifstream infile(fileName);
if (!infile)
{
std::cout << "Error: File name [" << fileName << "] not found!" << std::endl;
return 0;
}
// File stream inputs text file into array, then takes it out if the word is already stored
while(!infile.eof())
{
element * curr = nullptr;
temp = new element;
temp->next = nullptr;
infile >> temp->word;
if(head == nullptr){ // If list is empty, head becomes the first node
head = temp;
head->count++;
} else { // but if the list isn't empty
curr = head; // the current element goes inti the list
while (curr->next != nullptr){
if(curr->word == temp->word){ // If a duplicate it detected
curr->count++; // The count increases
delete temp;
temp = nullptr; // and temp becomes null
break;
}else{
curr = curr->next;
if(curr->word == temp->word){ // make sure to check the last element
curr->count++; // increase the count
delete temp;
temp = nullptr; // and temp becomes null
break;
}
}
}
if(temp != nullptr && temp->word != ""){ // if none of those conditions are met
curr->next = temp; // then the new element gets put into the list
curr->next->count++; // and the count automatically goes to 1
}
}
}
// Display the list using the current element istead of a for loop
temp = head;
while(temp != nullptr) {
std::cout << "Word: [ " << temp->word << " ] appears " << temp->count << " time(s)." << std::endl;
temp = temp->next;
}
// Delete memory allocated to the list
while(head != nullptr) {
temp = head->next;
delete head;
head = temp;
}
return 0;
}