[LeetCode] Remove Nth Node From End of List

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

Remove Nth Node From End of List

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

For 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. Try to do this in one pass.

思路

利用slow, fast双指针。首先fast先走n步,让slow和fast的距离为n,如果fast跑到最后为null的时候,slow正好是要删除的节点,因为这里要删除节点,所以让fast.next == null的时候,slow正好是要删除的节点的前一个节点,这时让slow.next = slow.next.next。这里要注意的是如果正好要删除的点是head,那么就没有一个pre的节点,这时要让head = head.next。

代码

public ListNode removeNthFromEnd(ListNode head, int n) {
    //corner case
    if(head == null || head.next == null) return null;
    ListNode fast = head, slow = head;
    //keep distance n from slow to fast
    for(int i = 0; i < n; i++){
        fast = fast.next;
        //when the deleteNode is the head node, so we can't keep the pre node, we need to have a new head
        if(fast == null){
            head = head.next;
            return head;
        }
    }
    //we need to find the preDeleteNode, so we need fast to stop at the last node
    while(fast.next != null){
        slow = slow.next;
        fast = fast.next;
    }
    slow.next = slow.next.next;
    return head;
}

脚本宝典总结

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

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

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