反向链表- c++
Reversing Linked List - 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;
}
}
您的代码接近了,它提前返回了。
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;
}
今天每个人都必须有相同的家庭作业。
我认为向这些人展示当列表被反转时,列表的状态会发生什么变化会更有帮助。这应该比向他们展示代码或代码问题更能帮助他们。
下面是应该发生的事情(我将使用的算法)
[] = head() = current
([1]) -> 2 -> 3 -> 4,[2] -> (1) -> 3 -> 4,[3] -> 2 -> (1) -> 4,[4]->3->2->(1)完成了,因为现在没有新的next
很抱歉回复晚了,我相信你现在已经找到了答案,但它可能对其他人有帮助。答案是简单地采取返回语句(即返回头;)while循环将解决你的问题。尽管有一些方法可以避免额外的指针和赋值来优化代码。
相关文章:
- 反向给定链表中的K节点
- 如果没有malloc,链表实现将失败
- 文本文件中的单词链表
- 努力将整数转换为链表。不知道我在这里做错了什么
- 链表,反向函数,数据结构
- 使用std::list创建循环链表
- 链表的泛型函数remove()与成员函数remove)
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 我们可以删除链表中静态内存中的节点吗
- C++,指针数组,指向双链表中的条目
- 链表中写入访问冲突的未知原因
- 如何修复链表类实现的未处理异常0xDDDDDDDD
- 打印所有链表的元素 (C++)
- 错误:需要类名(链表c++)
- 为什么C中的通用链表中存储的数据已损坏
- C++ 创建包含链表和字符串的对象的链接列表时出错
- 链表c++插入,所有情况都已检查,但没有任何工作
- 链表,将列表复制到另一个列表
- 为什么C++对链表中的下一个节点使用指针,而像 C# 或 Java 这样的语言只使用类 Node 的名称?
- 对单向链表进行排序时出现运行时错误