算法19. Remove Nth Node From End of List

19. Remove Nth Node From End of List

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

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.

Note:
Given n will always be valid.

移除链表倒数第n个节点。
n,肯定是合法的。

解:
这个题呢,可以取巧:取两个节点,都从开始遍历,第一个节点呢先走n步,然后再与第二个节点一起遍历,等到第一个节点到末尾了,那么第二个节点就正好是倒数第n个了,移除该节点即可。

以下是代码:

public ListNode removeNthFromEnd(ListNode head, int n) {
    ListNode start = new ListNode(0);
    ListNode slow = start, fast = head;
    slow.next = head;

    while (n != 0) {
        fast = fast.next;
        n--;
    }

    while (fast != null) {
        fast = fast.next;
        slow = slow.next;
    }
    // 删除该节点该节点
    slow.next = slow.next.next;
    return start.next;
}

你可能感兴趣的:(算法19. Remove Nth Node From End of List)