在LinkedList.h中,我有以下代码:
#ifndef LINK_H
#define LINK_H
template<typename T>
struct Node
{
T data;
Node *link;
};
#endif
在我的Main.cpp中,我有以下代码:
int size = 1;
int data = 0;
cout << "How big for linked list? ";
cin >> size;
cout << endl;
Node<int> *head;
Node<int> *node = new Node<int>[size];
head = &node[0];
for (int i = 0; i < size; i++)
{
cout << "Input data for link " << i + 1 << ": ";
cin >> node[i].data;
if (i < size - 1)
node[i].link = &node[i + 1];
else
node[i].link = NULL;
}
Node<int> *ptr = head;
cout << "Linked list has current data: ";
while (ptr)
{
cout << ptr->data << " ";
ptr = ptr->link;
}
cout << endl << endl << "What data do you want to add to the front of the list? ";
cin >> data;
cout << endl;
//add
Node<int> *loc = new Node<int>;
loc->data = data;
loc->link = head;
head = loc;
cout << "Linked list has current data: ";
ptr = head;
while (ptr)
{
cout << ptr->data << " ";
ptr = ptr->link;
}
cout << endl << endl << "Deleting the data you just added." << endl;
//delete single
Node<int> *temp = new Node<int>;
temp = head;
head = head->link;
delete temp;
cout << "Linked list has current data: ";
ptr = head;
while (ptr)
{
cout << ptr->data << " ";
ptr = ptr->link;
}
cout << endl;
//delete entire list
ptr = head;
while (ptr)
{
cout << "/";
Node<int> *old = new Node<int>;
old = ptr;
ptr = ptr->link;
delete old;
}
cout << endl;
尝试取消分配此链接列表时,出现错误,如标题中的错误,程序崩溃。似乎c ++试图访问它不再有权访问的内存,它与我的loc指针/添加到列表前面的新链接有关。谁能告诉我我的代码出错了?说删除代码的部分基本上只是用来打印链表中的内容。
编辑:错误发生在最后一次while循环的2次迭代之后。
Edit2:在我拨打电话后似乎:
delete temp;
头失去了链接并返回垃圾。为什么呢?