javascript-leetcode icon indicating copy to clipboard operation
javascript-leetcode copied to clipboard

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

Open Geekhyt opened this issue 4 years ago • 1 comments

原题链接

快慢指针

先明确,删除倒数第 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 avatar Jan 31 '21 14:01 Geekhyt

//老师指导一下呗
// 感觉我写的不是很易懂,快慢指针好太多了~哎
/*
 * @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


GTRgoSky avatar Jan 19 '22 08:01 GTRgoSky