Problem

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

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?

Note

首先建立dummy结点指向head,复制链表。
然后建立快慢指针结点fastslow,让fastslow先走n个结点,再让fastslow一起走,直到fast到达链表最后一个结点。由于fastslown个结点,所以slow正好在链表倒数第n+1个结点
最后让slow指向slow.next.next,就删除了原先的slow.next———倒数第n个结点
返回dummy.next,结束。

Solution

class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null || n <= 0) return head;
        ListNode dummy = new ListNode(0);
        dummy.next = head;
        ListNode slow = dummy, fast = dummy;
        while (n-- != 0) {
            fast = fast.next;
        }
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
    }
}

linspiration
161 声望53 粉丝

引用和评论

4 条评论
头像
VitoDiao

你好,我想问个问题,最后为什么要返回dummy.next 作为结束?而不是slow或者slow.next为结束,整个程序就这里不太明白,谢啦

2017-02-01
linspiration(作者)

@VitoDiao slow的位置变了啊 dummy还是伪头结点

2017-02-01
VitoDiao

@VitoDiao @linspiration 那么dummy.next代表的是新的链表的头节点的后继元素?

2017-02-01
2017-02-01