Remove Nth Node From End of List(lintcode 174)

Description

Given a linked list, remove the nth node from the end of list and return its head.

Notice:
The minimum number of nodes in list is n.

Example

Given linked list: 1->2->3->4->5->null, and n = 2.

After removing the second node from the end, the linked list becomes 1->2->3->5->null.

Interface

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
    }
}

Idea

Use two references here. Both of them pointed to dummy node before start. The fast one run n step first. Then both of them run together until the fast reference pointed to the last node. Now the slow one pointed to the n-1th node.

Solution

/**
 * Definition for ListNode.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int val) {
 *         this.val = val;
 *         this.next = null;
 *     }
 * }
 */ 
public class Solution {
    /**
     * @param head: The first node of linked list.
     * @param n: An integer.
     * @return: The head of linked list.
     */
    ListNode removeNthFromEnd(ListNode head, int n) {
        // write your code here
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        head = dummy;
        ListNode fast = head;
        for (int i = 0; i < n; ++i) {
            fast = fast.next;
        }

        while (fast.next != null) {
            fast = fast.next;
            head = head.next;
        }

        head.next = head.next.next;
        return dummy.next;
    }
}

results matching ""

    No results matching ""