美文网首页
19. Remove Nth Node From End of

19. Remove Nth Node From End of

作者: 窝火西决 | 来源:发表于2019-05-29 21:38 被阅读0次

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个元素的前驱,传统方法删除即可。
若从head开始遍历,则需要考虑n=1的情况,也就是慢指针指向最后一个节点并删除。

代码

public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null)
            return null;
        ListNode dummy = new ListNode(0);
        ListNode fast = dummy, slow = dummy;
        dummy.next = head;
        for (int i = 0; i < n; ++i)
            fast = fast.next;
        while (fast.next != null) {
            slow = slow.next;
            fast = fast.next;
        }
        slow.next = slow.next.next;
        return dummy.next;
}

相关文章

网友评论

      本文标题:19. Remove Nth Node From End of

      本文链接:https://www.haomeiwen.com/subject/qgvutctx.html