反转链表 - C ++ [英] Reversing Linked List - C++
本文介绍了反转链表 - C ++的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我写了一个函数,应该颠倒一个列表。
I wrote a function that should reverse a list.
到目前为止,我只能反转两个项目,但没有更多。我检查和双检查,仍然找不到问题。我甚至使用调试器来查看每个指针的值。运行调试器时,我收到了以下消息:
So far, I can reverse only two items, but no more. I checked and double checked and still can't find the problem. I even used the Debugger to see the value of each pointer. When running the debugger, I received the message:
程序中出现访问冲突(分段错误)。
An access violation (segmentation fault) raised in your program.
这是我第一次使用链接列表的作业,所以我还在学习。
This is my first assignment with linked lists so I am still learning.
我在Dev-C ++中写道:
Here is the code I wrote in 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;
}
}
推荐答案
代码关闭,它早退了。
Your code is close, it is returning early.
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 ++的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文