反转链表的每个 K 元素时的分段错误
Segmentation fault while reversing every K elements of a linkedlist
我正在尝试反转C++中的链表。具体问题陈述是这样的:给定一个单向链表和一个整数K
,一次反转列表K
的节点,并返回修改后的链表。
示例:给定链表:1 -> 2 -> 3 -> 4 -> 5 -> 6 和 K=2
,
修改后的链表应为:2 -> 1 -> 4 -> 3 -> 6 -> 5。
但是我的代码遇到了分段错误。我尝试了一切,但无法弄清楚出了什么问题。请帮忙。蒂亚。
我的代码:
#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
ListNode* reverseSubList(ListNode* prev, ListNode* start, int sz){
ListNode *current, *next;
current = start;
while (sz>0) {
next = current->next;
current->next = prev;
prev = current;
current = next;
sz--;
}
return prev;
}
ListNode* reverseList(ListNode* A, int B) {
ListNode *start, *end;
int i;
start = A;
end = NULL;
while (start!=NULL) {
end = reverseSubList(end, start, B); //end stores the first element of the last k elements reversed.
start = end->next;
}
return end;
}
int main() {
ListNode *linkedlist = new ListNode(10);
ListNode *temp, *next;
temp = linkedlist;
int i=9;
while (i>0) {
next = new ListNode(i*2);
temp->next = next;
temp = temp->next;
i--;
}
for (temp=linkedlist; temp->next!= NULL; temp = temp->next)
cout<<temp->val<<" ";
next = reverseList(linkedlist, 3);
cout<<"n";
for (temp=next; temp->next!= NULL; temp = temp->next)
cout<<temp->val<<" ";
return 0;
}
我的调试器告诉我,current
在某个时候是 NULL(见下文(,取消引用NULL
指针是 UB(通常以段错误结束(。
ListNode* reverseSubList(ListNode* prev, ListNode* start, int sz) {
ListNode *current, *next;
current = start;
while (sz>0) {
next = current->next; // <<< current can be NULL here
....
要调试,请像这样修改:
ListNode* reverseSubList(ListNode* prev, ListNode* start, int sz) {
ListNode *current, *next;
current = start;
while (sz>0) {
if (current == NULL)
{
printf("Fixme");
exit(1);
}
next = current->next; // <<< current can be NULL here
....
或者更好:了解如何使用调试器并使用它。它将很快得到回报。
相关文章:
- Mongodb c++驱动程序:如何查询元素的数组
- 分段故障(堆芯转储)矢量
- 将数组作为参数传递给函数安全吗?作为第三方职能部门,可以探索他们想要的之外的其他元素
- 使用strcpy将char数组的元素复制到另一个数组
- 使用不带参数的函数访问结构元素
- 给定n个元素的m个集合.在C++中找到出现在最大集合数中的元素
- 数组的指针从不分段故障
- C++如何通过用户输入删除列表元素
- 用于查找数组中最大元素的出现次数的代码,给出分段错误
- 基于相邻元素 c++ 的分段误差范围的循环
- 反转链表的每个 K 元素时的分段错误
- 我写了此方法来删除链接列表的重复元素,但它显示了分段故障,原因
- 字符串具有 16 个或更多元素时的分段错误
- 将元素添加到现有结构会使函数在分段错误时崩溃
- 尝试从列表中删除元素时出现分段错误
- 当我在 C++ 中推回矢量类上的元素时出现分段错误
- 访问数组中的第二个元素时,c++中的分段错误11
- 在字符串数组中计数元素时出现分段错误
- Cuda Thrust获得分段中的前一个元素
- 嵌套循环中的分段错误,用于使用矢量中的每2个元素进行计算