My one pass solution


  • 37
    X
    public ListNode RemoveNthFromEnd(ListNode head, int n) {
        ListNode h1=head, h2=head;
        while(n-->0) h2=h2.next;
        if(h2==null)return head.next;  // The head need to be removed, do it.
        h2=h2.next;
        
        while(h2!=null){
            h1=h1.next;
            h2=h2.next;
        }
        h1.next=h1.next.next;   // the one after the h1 need to be removed
        return head;
    }

  • 0

    Thanks for your post not using the dummy head node !


  • 0
    N

    It's not working


  • 0
    R
    This post is deleted!

  • 0
    Y

    It's a very good solution that avoids using a fake head!


  • 0
    A

    This solution (as many other from this task) do not remove Nth element from, but just plays with pointers. After this

    h1.next=h1.next.next
    

    we will have to nodes pointing to the same one (one is from list other is a 'dead' one):

          x<- to remove    
    1->2->3->4->
    
       1->3->4->
       2->3->4->
    

    Java garbage collector will keep this 'dead (2->)' pointer in memory till node with value 3 will be not null.

    th2 = h1.next;
    h1.next=h1.next.next;
    h2.next = null;
    

    can help


Log in to reply
 

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