我有一个列表,我想显示它的值。
我希望看到1 2 3 4
,但我有一个无限循环,如1 2 3 4 1 2 3 4 1 2..
无法理解,为什么?
struct node
{
int item;
node *next;
node(int x, node *t)
{
item = x;
next = t;
}
};
int main()
{
node *firstElement = new node(1, NULL);
firstElement->next = firstElement;
node *lastElement = firstElement;
for (int i = 2; i < 5; i++)
lastElement = (lastElement->next = new node(i, firstElement));
for (node *first = lastElement; first != 0; first = first->next)
cout << first->item << " ";
delete firstElement;
return 0;
}
答案 0 :(得分:2)
尝试使用此代码:
struct node
{
int item;
node *next;
node(int x, node *t)
{
item = x;
next = t;
}
};
int main()
{
node *firstElement = new node(1, NULL);
node *lastElement = firstElement;
for (int i = 2; i < 5; i++)
lastElement = (lastElement->next = new node(i, nullptr));
for (node *first = firstElement; first != 0; first = first->next)
cout << first->item << " ";
return 0;
}
问题是您将最后一个节点的“下一个”链接设置为此节点本身,而不是nullptr 此外,最好删除分配的内存
答案 1 :(得分:2)
问题是你的数据结构本身有一个无限循环:这一行
firstElement->next = firstElement;
使firstElement
指向自身,创建循环列表。当您添加更多元素时,您的列表将保持循环,因此永远不会实现退出条件first == 0
。
如果您希望列表保持线性而不是循环,则应按如下方式修改插入代码:
node *firstElement = new node(1, NULL);
node *lastElement = firstElement;
for (int i = 2; i < 5; i++) {
lastElement->next = new node(i, lastElement->next)
lastElement = lastElement->next;
}
打印代码应以firstElement
开头:
for (node *current = firstElement; current != 0; current = current->next)
cout << current->item << " ";
最后,删除单个firstItem
是不够的。你需要一个循环来遍历整个列表。或者,您可以通过调用delete next
在析构函数中链接删除,但这很危险,因为析构函数的递归调用可能会溢出堆栈。
答案 2 :(得分:1)
您的列表中有一个循环,因为lastElement->next
始终指向firstElement
。这就是first
永远不会等于0
。
如果你真的需要一个循环我认为你应该写这样的东西:
node* p = firstElement;
do {
cout << p->item << " ";
p = p->next;
} while (p != firstElement);
答案 3 :(得分:1)
问题是您使用firstElement
作为其next
创建每个节点
如果您要将节点添加到列表的前面,这是有意义的,但是您在后面添加它们,因此最后一个节点将指回到开始。
由于您要添加到后面,请在每次插入时终止列表:
lastElement->next = new node(i, nullptr))