Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
webVueBlog opened this issue Sep 2, 2022 · 0 comments
Open

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

webVueBlog opened this issue Sep 2, 2022 · 0 comments

Comments

@webVueBlog
Copy link
Owner

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

Description

Difficulty: 中等

Related Topics: 链表, 双指针

给你一个链表,删除链表的倒数第 n个结点,并且返回链表的头结点。

示例 1:

输入:head = [1,2,3,4,5], n = 2
输出:[1,2,3,5]

示例 2:

输入:head = [1], n = 1
输出:[]

示例 3:

输入:head = [1,2], n = 1
输出:[1]

提示:

  • 链表中结点的数目为 sz
  • 1 <= sz <= 30
  • 0 <= Node.val <= 100
  • 1 <= n <= sz

**进阶:**你能尝试使用一趟扫描实现吗?

Solution

Language: JavaScript

/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 * 快慢指针法
 */
var removeNthFromEnd = function(head, n) {
    const dummy = new ListNode(-1, head)
    let [slow, fast] = [dummy, dummy]

    for (let i = 0; i <= n; i++) {
        fast = fast.next
    }

    while (fast) {
        slow = slow.next
        fast = fast.next
    }

    slow.next = slow.next.next

    return dummy.next
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant