Sunday, December 22, 2013

Leetcode: Remove Nth Node From End of List

Given a linked list, remove the nth node from the end of list and return its head.
For example,
   Given linked list: 1->2->3->4->5, and n = 2.

   After removing the second node from the end, the linked list becomes 1->2->3->5.
Note: Given n will always be valid.

Our solution

Our algorithm is based on two pointers, denoted by pointerEnd and pointerBegin, Both pointers traverse the list distanced by n elements. When the pointerEnd reaches the last element, the pointerBegin points to the previous element than the one to remove.
Again, we use the trick of a dummy node at the beginning so the algorithm is identical for all the cases and we remove it at the end.

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        ListNode head2 = new ListNode(0);
        head2.next = head;
        ListNode pointerEnd = head2, pointerBegin = head2;

        // We advance pointerEnd n positions
        for(int i=0; i<n; i++)
            pointerEnd = pointerEnd.next;

        //We advance both elements at the same speed
        while(pointerEnd.next != null)
        {
            pointerBegin = pointerBegin.next;
            pointerEnd = pointerEnd.next;
        }

        pointerBegin.next=pointerBegin.next.next;
        return head2.next;
    }
}

No comments :

Post a Comment