反转链表 - C++
我编写了一个应该反转列表的函数。
到目前为止,我只能逆转两项,但不能再逆转了。我检查了又仔细检查,仍然找不到问题。我什至使用调试器来查看每个指针的值。运行调试器时,我收到消息:
程序中出现访问冲突(分段错误)。
这是我的第一个链表作业,所以我仍在学习。
这是我在 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;
}
}
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.
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;
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您的代码已接近,它会提前返回。
Your code is close, it is returning early.
今天每个人都必须有相同的家庭作业。
我认为,向这些人展示列表状态在反转时会发生什么情况会更有帮助。这应该比向他们展示代码或代码问题更好地帮助他们。
这是应该发生的情况(使用我将使用的算法)
[] = head
()=当前
([1])->2->3->4,
[2]->(1)->3->4,
[3]→2→(1)→4,
[4]->3->2->(1) 已完成,因为当前当前没有新的下一个
Everyone must have the same homework assignment today.
I think it would be more helpful to these people to show them what happens to the state of the list while it is being reversed. This should help them better than showing them code or code problems.
Here is what should happen (with the algorithm I would use)
[] = head
() = current
([1])->2->3->4,
[2]->(1)->3->4,
[3]->2->(1)->4,
[4]->3->2->(1) done because current now doesn't have a new next
抱歉回复晚了,我相信您现在已经找到答案了,但它可能对其他人有帮助。答案是简单地从 while 循环中取出 return 语句(即 return head;)即可解决您的问题。尽管有一些方法可以避免额外的指针和赋值来优化代码。
Sorry for answering late and I am sure that you would have found the answer by now but yet it might be helpful for others. Answer is simply taking return statement (i.e. return head;) out of while loop will fix your problem. Though there are ways you can avoid extra pointer and assignments to optimise your code.