Remove Nth Node From End of List 174

Question

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.

Challenge

Can you do it without getting the length of the linked list?

Solution

这道题一开始可以考虑reverse之后再删去第n个。

如果只能走一趟,那可以用two pointer。总体思想为:要删去从后往前第n个元素,即删去从前往后第size-n+1个元素。一个指针先从前往后走n步,然后此时从n到list尾部(null)的距离为size-n+1,这时候另一个指针从dummy(第一个元素之前的元素)和第一个指针一起往后移动直到第一个指针到达list尾部为止,此时第二个指针到达第size-n个元素,只要删去其后面的元素即可。

代码如下:

public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (n <= 0) {
            return null;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;

        ListNode preDelete = dummy;
        for (int i = 0; i < n; i++) {
            if (head == null) {
                return null;
            }
            head = head.next;
        }
        while (head != null) {
            head = head.next;
            preDelete = preDelete.next;
        }
        preDelete.next = preDelete.next.next;
        return dummy.next;
    }
}

results matching ""

    No results matching ""