Runtime error while creating a node in Leetcode problem 25 (Reverse Nodes in k-Group)

  Kiến thức lập trình

I was solving the leetcode problem 25 Reverse Nodes in k-group where I tried to submit the following code in C++ :

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    void reverseList(ListNode *head){
        ListNode *prev=NULL,*cur=head,*Next;
        while(cur){
            Next=cur->next;
            cur->next=prev;
            prev=cur;
            cur=Next;
        }
        return ;
    }
    ListNode* reverseKGroup(ListNode* head, int k) {
        if(head->next == NULL || k==1) return head;

        ListNode *prev=new ListNode();
        prev->next=head;
        ListNode *cur=prev,*Next;
        head=prev;

        while(Next){
            for(int i=1;i<=k;i++){
                if(cur==NULL) return head->next;
                else cur=cur->next;
            }

            Next=cur->next;
            cur->next=NULL;
            reverseList(prev->next);
            ListNode *tail=prev->next;
            tail->next=Next;
            prev->next=cur;
            cur=tail;
            prev=tail;
        }
        return head->next;
    }
};

While submitting I got the following RuntimeError

Line 27: Char 15: runtime error: store to address 0x5020000000f8 with insufficient space for an object of type 'ListNode *' (solution.cpp)
0x5020000000f8: note: pointer points here
 be be be be  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00 00 00 00 00  00 00 00 00
              ^
SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior solution.cpp:27:15

The line no 27 is prev->next=head
I am not sure why this error encountered, I have used this syntax in other problems without any errors but here, in this problem, I don’t know why the error occurred.
Please help.

LEAVE A COMMENT