Leetcode–Remove Nth Node From End of List

The Problem:

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.

Notes:

  1. Two pointers with one n elements ahead, so when the faster reach the end, the slower one is the one to delete.
  2. It can be the head to delete, use a fake head trick.

Java Solution:

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head==null) return head;
        ListNode fkHead = new ListNode(0);
        fkHead.next = head;
        ListNode p = head;
        while(n>0){
            p = p.next;
            n--;
        }
        ListNode pre = fkHead;
        ListNode current = head;
        while(p!=null){
            p = p.next;
            pre = pre.next;
            current = current.next;
        }
        pre.next = current.next;
        return fkHead.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