【发布时间】:2011-10-26 00:07:28
【问题描述】:
我写了一个可以反转列表的函数。
到目前为止,我只能反转两个项目,但不能再反转了。我检查并仔细检查,仍然找不到问题。我什至使用调试器查看每个指针的值。运行调试器时,我收到消息:
程序中出现访问冲突(分段错误)。
这是我的第一个链表作业,所以我还在学习。
这是我用 Dev-C++ 编写的代码:
List::ListNode *List::Reverse_List(ListNode *head)
{
ListNode *cur = head;
ListNode *forward = NULL;
ListNode *previous = NULL;
while (cur != NULL)
{
head = cur; //set the head to last node
forward = head->next; //save the next pointer in forward
cur->next = previous; //change next to previous
previous = cur;
cur = forward;
cout << "cur= " << cur->item << endl; //this is just to display the current value of cur
return head;
}
}
【问题讨论】:
-
成员函数返回的最后一个节点是什么?您如何将反向列表头节点的前一个元素设置为 NULL ?
-
哎呀!我的错,我忘了返回 *head;我将编辑代码。谢谢。
-
但是程序停止工作。我仍然无法找出问题所在。
-
此外,在编译源代码后,我还收到消息:"[Linked error] undefined reference to 'WinMain@16' ID returned 1 exit status。我仍然找不到原因消息。
-
将
return head;退出循环,它会在一次迭代后返回。向我们展示ListNode的声明,如果每个节点都存储一个next 和一个previous 指针,那么它会相当简单。