反转链表的每个 K 元素时的分段错误

Segmentation fault while reversing every K elements of a linkedlist

本文关键字:元素 分段 错误 链表      更新时间:2023-10-16

我正在尝试反转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
  ....

或者更好:了解如何使用调试器并使用它。它将很快得到回报。