我正在尝试做一个 int 值的链接列表。我将 3 个 int 值添加到列表中,然后打印它们,但打印 3 个值后出现问题,程序返回打印函数以打印第 4 个值,因为 (tempNode != NULL) 给出 true 但打印后应该为 NULL 3个值,所以它给我打印方法中的访问冲突读取错误cout << "index " << size-- << ", value: "<< tempNode->num << endl;
它超出了我的列表节点,但我不知道哪里做错了。
请帮助,2天我试图解决这个问题。
下面的代码。
IntList::IntList()
{
first = NULL;
last = NULL;
size = 0;
}
IntList::Node::Node(const int& info, Node* next = NULL)
{
num = info;
next = next;
}
IntList::~IntList()
{
Node* tempNode = first;
while ( tempNode != NULL )
//for(int i = 0; i < size; i++)
{
Node* nextNode = tempNode->next;
delete tempNode;
tempNode = nextNode;
}
first = last = NULL;
size = 0;
}
IntList::IntList(const IntList& wl)
{
cout << "here word list copy conts " << endl;
first = last = NULL;
size = wl.size;
if(wl.first != NULL){
Node* tempNode = wl.first;
for(int i = 0; i < wl.size; i++)
{
addLast(tempNode->num);
tempNode = tempNode->next;
}
}
}
IntList& IntList::operator = (const IntList& wl)
{
cout << "here word list =" << endl;
if(this == &wl)
return *this;
Node* tempNode = first;
while ( tempNode != NULL )
{
Node* nextNode = tempNode->next;
delete tempNode;
tempNode = nextNode;
}
first = NULL;
last = NULL;
if(wl.first != NULL)
{
for(int i = 0; i < wl.size; i++)
{
addLast(tempNode->num);
tempNode = tempNode->next;
size++;
}
}
return *this;
}
void IntList::addFirst(int& winfo)
{
Node* firstNode = new Node(winfo);
//Node firstNode(winfo);
if(first == NULL)
{
first = last = firstNode;
}
else
{
firstNode->next = first;
first = firstNode;
}
//increment list size
size++;
}
void IntList::print(ostream& out)
{
Node* tempNode = first;
while ( tempNode != NULL )
{
out << "\t";
cout << "index " << size-- << ", value: "<< tempNode->num << endl;
tempNode = tempNode->next;
}
}