Skip to content

删除链表的倒数第 N 个结点 #18

Open
@Bulandent

Description

@Bulandent

难度:中等
来源:19. 删除链表的倒数第 N 个结点

给你一个链表,删除链表的倒数第 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

**题解一:第一次遍历计算出链表长度,然后第二次遍历 count - n - 1 次 **

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let count = 0, temp = head
    // 计算出链表长度 count
    while (temp) {
        temp = temp.next
        count++
    }
    count = count - n - 1
    if (count == -1) return head.next
    temp = head
    while (count > 0) {
        temp = temp.next
        count--
    }
    temp.next = temp.next.next
    return head
}

题解二:双指针

/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let first = second = head
    while ( n > 0 ) {
        first = first.next
        n--
    }
    if (!first) return head.next
    while ( first.next !== null ) {
        first = first.next
        second = second.next
    }
    second.next = second.next.next
    return head
};

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions