Skip to content

19. 删除链表的倒数第 N 个结点 #12

@Geekhyt

Description

@Geekhyt

原题链接

快慢指针

先明确,删除倒数第 n 个结点,我们需要找到倒数第 n+1 个结点,删除其后继结点即可。

1.添加 prev 哨兵结点,处理边界问题。
2.借助快慢指针,快指针先走 n+1 步,然后快慢指针同步往前走,直到 fast.next 为 null。
3.删除倒数第 n 个结点,返回 prev.next。

const removeNthFromEnd = function(head, n) {
    let prev = new ListNode(0), fast = prev, slow = prev;
    prev.next = head;
    while (n--) {
        fast = fast.next;
    }
    while (fast && fast.next) {
        fast = fast.next;
        slow = slow.next;
    }
    slow.next = slow.next.next;
    return prev.next;
}
  • 时间复杂度:O(n)
  • 空间复杂度:O(1)

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      pFad - Phonifier reborn

      Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

      Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


      Alternative Proxies:

      Alternative Proxy

      pFad Proxy

      pFad v3 Proxy

      pFad v4 Proxy