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

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


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

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

  • 0

    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.