[LeetCode/LintCode] Remove Nth Node From End of List

发布时间:2019-06-16 发布网站:脚本宝典
脚本宝典收集整理的这篇文章主要介绍了[LeetCode/LintCode] Remove Nth Node From End of List脚本宝典觉得挺不错的,现在分享给大家,也给大家做个参考。

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;
    }
}

脚本宝典总结

以上是脚本宝典为你收集整理的[LeetCode/LintCode] Remove Nth Node From End of List全部内容,希望文章能够帮你解决[LeetCode/LintCode] Remove Nth Node From End of List所遇到的问题。

如果觉得脚本宝典网站内容还不错,欢迎将脚本宝典推荐好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。
标签: