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 个结点 #12

Open
Geekhyt opened this issue Jan 31, 2021 · 1 comment
Open

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

Geekhyt opened this issue Jan 31, 2021 · 1 comment
Labels

Comments

@Geekhyt
Copy link
Owner

Geekhyt commented Jan 31, 2021

原题链接

快慢指针

先明确,删除倒数第 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)
@Geekhyt Geekhyt added the 中等 label Jun 4, 2021
@GTRgoSky
Copy link

GTRgoSky commented Jan 19, 2022

//老师指导一下呗
// 感觉我写的不是很易懂,快慢指针好太多了~哎
/*
 * @lc app=leetcode.cn id=19 lang=javascript
 *
 * [19] 删除链表的倒数第 N 个结点
 */

// @lc code=start
/**
 * 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) {
    let $head = head;
    // 获取长度
    let len = 1;
    while($head.next) {
        $head = $head.next;
        len++;
    }

    let use = len - n;
    if (use == 0) {
        return head.next;
    }
    $head = head;
    while (use > 1) {
        $head = $head.next;
        use--;
    }
    $head.next = $head.next.next;
    return head;
   
};
// @lc code=end


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

No branches or pull requests

2 participants