我正在尝试用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;
}
Run Code Online (Sandbox Code Playgroud)
任何帮助都表示赞赏,因为我已经结束了!
很明显,功能addToEnd是错误的
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;
}
Run Code Online (Sandbox Code Playgroud)
假设列表已经包含两个节点,并考虑函数内部的do-while循环.起初current_next!= null所以执行以下语句
current = current->next;
Run Code Online (Sandbox Code Playgroud)
现在当前指向第二个节点.其数据成员next等于NULL.所以循环的条件
} while (current->next != NULL);
Run Code Online (Sandbox Code Playgroud)
将是错误的,不会重复迭代.所以我们什么都没说.
如果node不等于NULL,则该函数也不返回任何内容.
以下列方式重写该功能
listNode* addToEnd( listNode* node )
{
listNode* newNode = new listNode { ++nodeCount, NULL };
if ( node == NULL) return newNode;
listNode* current = node;
while ( current->next != NULL ) current = current->next;
current->next = newNode;
return newNode;
// or
//return node;
}
Run Code Online (Sandbox Code Playgroud)
考虑到这个说法
cout<<"Third: "<<first->next->next->val;
Run Code Online (Sandbox Code Playgroud)
仅输出第三个节点的值.如果要输出所有列表,则应编写
for ( listNode *current = first; current; current = current->next )
{
std::cout << current->val << ' ';
}
std::cout << std::endl;
Run Code Online (Sandbox Code Playgroud)
顺便说一句,使用我的函数,您可以在main中编写,例如以下方式:)
listNode* first;
addToEnd( addToEnd( addToEnd( addToEnd( first = addToEnd( NULL ) ) ) ) );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
146 次 |
| 最近记录: |