我写了一个函数来反转列表。
到目前为止,我只能反转两个项目,但不能更多。我检查并仔细检查,仍然找不到问题。我什至使用调试器查看每个指针的值。运行调试器时,我收到消息:
An access violation (segmentation fault) raised in your program.
这是我的第一个链表作业,所以我还在学习。
这是我用 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;
}
}
最佳答案
您的代码已关闭,它正在提前返回。
List::ListNode *List::Reverse_List(ListNode *head)
{
ListNode *cur = head;
ListNode *forward = NULL;
ListNode *previous = NULL;
while (cur != NULL) {
//There is no need to use head here, cur will suffice
//head = cur; //set the head to last node
forward = cur->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
//don't return here you have only adjusted one node
//return head;
}
//at this point cur is NULL, but previous still holds the correct node
return previous;
}
关于c++ - 反转链表 - C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7897302/