【发布时间】:2014-08-01 22:47:47
【问题描述】:
我正在尝试在 C++ 中构建一个链表。我的理解是,我创建的代码应该创建一个节点,然后逐渐将 4 个链接到最后。不幸的是,虽然我希望看到 cout 结果为“12 123 1234 12345”,但我看到的是“12 12 12 12”,而且我主要无法遍历列表 - 它只是崩溃了。
我有以下代码:
struct listNode {
int val;
listNode* next;
};
int nodeCount = 0;
listNode* addToEnd(listNode* node) {
listNode* newNode = new listNode;
newNode->val = ++nodeCount;
newNode->next = NULL;
if (node == NULL) {
return newNode;
}
listNode* current = node;
cout<<"\n\n";
do {
if (current->next == NULL) {
current->next = newNode;
}
cout<<current->val<<"\n";
current = current->next;
} while (current->next != NULL);
cout<<current->val<<endl;
}
int main()
{
listNode* first = addToEnd(NULL);
addToEnd(first);
addToEnd(first);
addToEnd(first);
addToEnd(first);
cout<<"Third: "<<first->next->next->val;
}
感谢任何帮助,因为我无能为力!
【问题讨论】:
标签: c++ linked-list