Help needed, NullPointerException is thrown even when the null is checked


  • 0
    W
    public class Solution {
    public ListNode sortList(ListNode head) {
        if(head == null || head.next == null)
            return head;
        ListNode temp = head;
        while(temp.next != null)
        {
            temp = temp.next;
        }
        return sortListRange(head, null);
    }
    
    public ListNode sortListRange(ListNode s, ListNode e)
    {
        ListNode p = s;
        ListNode dummy = new ListNode(0);
        dummy.next = s;
        ListNode pre = dummy;
        ListNode pos = p;
        if(pos == null || pos.next == null)
            return s;
        while(pos.next != null && pos.next != e)
        {
            if(p.val > pos.next.val)
            {
                ListNode mm = pos.next;
                pos.next = pos.next.next;
                pre.next = mm;
                mm.next = p;
                pre = pre.next;
            }
            pos =  pos.next;
        }
        sortListRange(dummy.next, p);
        sortListRange(p.next, null);
        return dummy.next;
        
    }
    

    }

    I am using partition sort. I set the range from start index and end index.

    Line 35 while(pos.next != null && pos.next != e) is throwing null exception even previous line checked the null value. Any ideas?


  • 0
    D

    If I were to guess, the reason is the check before the while. You see, if your pos is itself null, then it's next has nothing pointing to it, resulting in trying to access a pointer that doesn't exist. So, I think it could first check if pos itself is null, then if not, check it's next.


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.