Search code examples
c++runtime-error

I am trying Odd Even linked list programming problem on Leet code, I am leetcode so I am unable to identify what this error is about


this is my code

class Solution {
public:
    ListNode* oddEvenList(ListNode* head) {
        ListNode* odd=head;
        ListNode* even=odd->next;
        ListNode* evenStart = even;
        
        while(odd->next!=NULL &&  even->next!=NULL)
        {
            odd->next = even->next;
            odd=odd->next;
            even=odd->next;
            even=even->next;
        }
        
        odd->next=evenStart;
        
        return head;
    }
};

and is showing error Line 18: Char 41: runtime error: member access within null pointer of type 'ListNode' (solution.cpp) SUMMARY: UndefinedBehaviorSanitizer: undefined-behavior prog_joined.cpp:27:41

Take a look at this screen shot


Solution

  • Your first few lines are assuming that the list has at least two elements.
    This is your first problem.

    If you fix that, note that all you know when you enter the loop body is that odd->next!=NULL && even->next!=NULL.
    On the first iteration, this means that the list has at least three elements.

    Let's draw a list and see what happens.
    "o" and "e" are odd and even, and the curly brace is the boundary to the unknown part of the list, which might not exist:

    1 -> 2 -> 3 -> { 4 -> 5 -> 6 ...
    o    e
    
    odd->next = even->next
    
    +---------+
    |         V
    1    2 -> 3 -> { 4 -> 5 -> 6 ...
    o    e
    
    odd = odd->next
    
    +---------+
    |         V
    1    2 -> 3 -> { 4 -> 5 -> 6 ...
         e    o         
    
    even = odd->next
    
    +---------+
    |         V
    1    2 -> 3 -> { 4 -> 5 -> 6 ...
              o      e
    

    Oops...

    even = even->next
    
    +---------+
    |         V
    1    2 -> 3 -> { 4 -> 5 -> 6 ...
              o           e
    

    Double oops.

    Work out the solution using pen(cil) and paper first.
    It's by far the best method to solve (and debug) pointer manipulation problems.
    I won't give you a solution, because how much fun would that be?