逆转链表的每个K元素时出现分段错误

时间:2017-05-24 12:43:26

标签: c++ pointers linked-list singly-linked-list

我试图在C ++中反转链表。具体问题陈述是这样的: 给定单链表和整数K,一次反转列表K的节点并返回修改后的链表。

示例:给定链表:1 - > 2 - > 3 - > 4 - > 5 - > 6和K=2

修改后的链表应为:2 - > 1 - > 4 - > 3 - > 6 - > 5.

但我的代码遇到了分段错误。我尝试了一切但却无法弄清楚什么是错的。请帮忙。 TIA。

我的代码:

#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;
}

1 个答案:

答案 0 :(得分:2)

我的调试器告诉我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
  ....

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