LeetCode 19 – Remove nth Node from End of List

Posted on December 25, 2013

Last updated on December 25, 2013

Solution to LeetCode Remove nth Node from End of List problem.

To do this in one pass: Start with a pointer \(i\) at the head of the list, and move it forward \(n\) times. Take another pointer \(j\), and start it off at the head of the list. While \(i\) is not null, move both pointers forward. When \(i\) becomes null, \(j\) is located the \(n\)’th node from the end of list.

public ListNode removeNthFromEnd(ListNode head, int n) {
  ListNode n1 = head;
  ListNode n2 = head;
  for(int i = 0; i < n; i++) n1 = n1.next;
  if(n1 == null){
    head = head.next;
  }
  else{
    while(n1.next != null){
      n1 = n1.next;
      n2 = n2.next;
    }
    ListNode next = n2.next;
    n2.next = next.next;
    next.next = null; // clean up 
  }
  return head;
}
Remove nth Node from End of List
Markdown SHA1: ad2d7462db2bc24f354419493e6d3c477b650659