美文网首页
LeetCode每日一题:remove nth node fro

LeetCode每日一题:remove nth node fro

作者: yoshino | 来源:发表于2017-07-05 09:51 被阅读15次

    问题描述

    Given a linked list, remove the n th 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.

    问题分析

    这道题只能遍历一次,很自然的想到了快慢指针,直接连接待删除点前后两个节点即可。java不用自己释放内存,让jvm处理。

    代码实现

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

    相关文章

      网友评论

          本文标题:LeetCode每日一题:remove nth node fro

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