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.
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }

        /*
         * Add a header will save lots of base case discussion
         */
        ListNode header = new ListNode(0);
        header.next = head;
        ListNode firstPointer = header;
        ListNode secondPointer = header; 

        while (n >= 0) {
            secondPointer = secondPointer.next;
            n--;
        }
        while (secondPointer != null) {
            secondPointer = secondPointer.next;
            firstPointer = firstPointer.next;
        }
        firstPointer.next = firstPointer.next.next;
        return header.next;
    }
}
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s