Глубокая копия двусвязного списка

У меня проблемы с созданием полной копии моего двусвязного списка. Это домашнее задание, поэтому я хотел бы знать, почему мой код не работает, а не получить рабочий код, который я не понимаю.

Вот мой класс:

#include "textAnalyzer.h"#include <string>
#include <iostream>
#include <sstream>

TextAnalyzer::Node* TextAnalyzer::createNode(const string& word, const int wordFrequency,
Node* const previous, Node* const next)
{
return new Node(word, wordFrequency, previous, next);
}
void TextAnalyzer::releaseNodes()
{
Node* del = tail;

while(tail != NULL)
{
tail = tail->previous;
tail->next = del;
delete del;
del = tail;
}

delete [] head;
delete [] tail;

head = tail = del = NULL;
}

void TextAnalyzer::copyNodes(Node* const copyHead)
{
head = new Node(*copyHead);
Node* iter = head->next;

for(Node* np = copyHead->next; np != NULL; np = np->next)
{
iter->next = new Node(*np);
iter = iter->next;
}

iter = NULL;
}

TextAnalyzer::TextAnalyzer():head(createNode("0",0,NULL,NULL)),tail(head)
{}

TextAnalyzer::TextAnalyzer(const TextAnalyzer& copyObject)
{
copyNodes(copyObject.head);
}

TextAnalyzer::~TextAnalyzer()
{
releaseNodes();
}

TextAnalyzer TextAnalyzer::operator=(const TextAnalyzer& assignObject)
{
return TextAnalyzer(assignObject);
}

void TextAnalyzer::insertWord(const string& word)
{
Node* iter = head->next;

while(iter != NULL)
{
if(iter->word == word)
iter->wordFrequency++;
else if(iter->word[0] == word[0] && iter->next != NULL)
{
Node* temp = iter->next;
iter->next = createNode(word, 1, iter, temp);
iter = iter->next;
temp->previous = iter;

temp = NULL;
}
else if(iter->word[0] == word[0] && iter->next == NULL)
{
iter = createNode(word, 1, tail, NULL);
tail = iter;
}
else
iter = iter->next;
}

iter = NULL;
}

int TextAnalyzer::wordCount() const
{
Node* iter = head->next;
int count = 0;

while(iter != NULL)
count++;

return count;
}

int TextAnalyzer::wordCountWithInitialCharacter(const char startsWith)
{
Node* iter = head->next;
int count = 0;

for(int i = 0; i < wordCount(); i++)
{
if(startsWith == iter->word[0])
count++;

iter->previous = iter;
iter = iter->next;
}

iter = NULL;

return count;
}

string TextAnalyzer::toString() const
{
Node* iter = head->next;
string desc = "List of words: \n";
ostringstream convert;

for(int i = 0; i < wordCount(); i++)
{
convert << iter->word[0] << " words:\n"<< iter->word    << "("<< iter->wordFrequency
<< ")\n";
iter->previous = iter;
iter = iter->next;
}

iter = NULL;

return desc + convert.str();
}

Вот интерфейс:

#ifndef TEXTANALYZER_H
#define TEXTANALYZER_H

#include <iostream>
#include <string>

using namespace std;

class TextAnalyzer {
private:

/*
* Class: Node
*
* This class represents a node in a sorted doubly linked list that stores a
* list of words and their frequency of occurrence.
*/
class Node {
public:
string word;
int wordFrequency;
Node* previous;
Node* next;

Node(const string& word,
const int wordFrequency,
Node* const previous,
Node* const next)
: word(word),
wordFrequency(wordFrequency),
previous(previous),
next(next)
{}
}; // end ListNode
/*********************************************************************/

Node* head;
Node* tail;/*
* Releases all the memory allocated to the list.
*/
void releaseNodes();

/*
* Makes a deep copy of the object.
*/
void copyNodes(Node* const copyHead);

/*
* Returns a populated Node.
* Throws a bad_alloc exception if memory is not allocated.
*/
Node* createNode(const string& word,
const int wordFrequency,
Node* const previous,
Node* const next);

public:
/*
* Initializes head and tail, each to a dymmy node.
*/
TextAnalyzer();

/*
* Makes a deep copy of the object passed in.
* Calls copyNodes() to do the actual work.
*/
TextAnalyzer(const TextAnalyzer& copyObject);

/*
* Releases all the memory allocated to the object.
* Calls the releaseNodes() method to do the actual work.
*/
~TextAnalyzer();

/*
* Makes a deep copy of the rhs object.
*/
TextAnalyzer operator =(const TextAnalyzer& assignObject);

/*
* Inserts the word in a sorted order into the list.
*
* If no Node exists with that initial character, one is added in
* sorted order. If one does exist (same word), then the word frequency
* of that word is incremented by one.
*/
void insertWord(const string& word);

/*
* Returns a count of all the words in the list.
*/
int wordCount() const;

/*
* Returns a count of all the words with the initial character.
*/
int wordCountWithInitialCharacter(const char startsWith);

/*
* Returns a description of the object. The string is formatted as:
* [A words:]
*     [<word>(<count>)]
*     [<word>(<count>)]
*     ...
*
* [B words:]
*     [<word>(<count>)]
*     [<word>(<count>)]
*     ...
*
*...
*/
string toString() const;

};

#endif

Я обязан использовать интерфейс, указанный выше. Моя проблема в том, что я получаю сообщение об ошибке в своем конструкторе копирования, в котором говорится: «У объекта есть классификаторы, которые не совместимы» или что-то подобное. Я предполагаю, что это потому, что copyObject постоянно. Тем не менее, я не знаю, как это сделать иначе, может кто-нибудь сказать мне, что мне здесь не хватает? Я довольно новичок в C ++, у меня больше опыта работы с Java, поэтому я могу запутаться.

РЕДАКТИРОВАТЬ:

Спасибо за ответы. Я думаю, что собирался выяснить, как успешно сделать глубокую копию. Я обновил свой код, чтобы показать, что я уже выполнил. Теперь, когда я скомпилировал код, я получил новую ошибку. «необработанное исключение 0xc0000005» каждый раз, когда я запускаю его. Я гуглил это и считаю, что это ошибка, вызванная попыткой разыменования нулевого указателя. Отладчик показывает, что он брошен в мой releaseNodes() метод.

void TextAnalyzer::releaseNodes()
{
Node* del = tail;

while(tail != NULL)
{
tail = tail->previous; //error on this line
tail->next = del;
delete del;
del = tail;
}

delete [] head;
delete [] tail;

head = tail = del = NULL;
}

Выше только мой releaseNodes() метод, с комментарием, показывающим, где отладчик говорит, что произошла ошибка. Я хотел бы посмотреть, работает ли остальная часть моего кода, так как я новичок в C ++, и очень вероятно, что моя логика имеет недостатки и в других местах, к сожалению, пока эта ошибка не будет устранена, я не могу ничего проверить. Я все еще прослеживаю свой код, пытаясь найти, что может быть причиной этого. Если кто-нибудь может указать мне правильное направление, это будет оценено.

0

Решение

Я предполагаю, что это строка, где говорится

void TextAnalyzer::copyNodes(Node* const copyHead)
{
head->next = new Node(*copyHead);
}

Вы просто назначаете следующему указателю в голове новый объект Node. По сути, вы копируете только один узел, узел, следующий за узлом, а не весь список. У вас есть правильное представление о том, что вы должны делать в releaseNodes с циклом while.

Также вы вызываете это неправильно в конструкторе копирования. Вы дали этому параметру в своем определении, но вы вызываете тот, который не принимает ни один в конструкторе.

0

Другие решения

Других решений пока нет …

По вопросам рекламы ammmcru@yandex.ru
Adblock
detector