Java 1ms solution, one pass with explanation


  • 1
    H

    public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode fast = head, slow = head;

            //advance fast by n nodes
        	while(fast!=null && n>0){
        		fast=fast.next;
        		n--;
        	}
           //if fast is null, it has crossed the tail and head needs to be removed.
        	if(fast==null)
        		return head.next;
          //traverse the list until fast reaches the last node, at the point slow will be at the previous node
          // from the nth node from last
        	while(fast.next!=null){
        		slow=slow.next;
        		fast=fast.next;
        	}
        	
           //bypass the nth node 
        	slow.next=slow.next.next;
        	
        	return head;
    }

Log in to reply
 

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