null pointer exception


  • 0
    F

    Hello everyone,

    I want to discuss my solution in which I am not using dummy node and in my code in line h2.next = h2.next.next there is a null pointer exception coming up. I think the h2 is null, can anyone please suggest me why this is happening because h2 points to the head node then why this is null??

    Following is my code

    ListNode h1 = head;
            ListNode h2 = head;
            ListNode current = head;
            int totalListCount = 1;
            
            while(n-->0)
                h1 = h1.next;
            
            if(h1==null) 
                return head.next;
            
            while( current.next!=null ) {
                current = current.next;
                totalListCount = totalListCount+1;
            }
            
            int finalCount = totalListCount-n;
            
            for(int i=1;i<finalCount;i++) {
                h2 = h2.next;
            }
            
            h2.next = h2.next.next;
            
            return head;
    

    I shall be waiting for your replies.

    Cheers.


Log in to reply
 

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