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

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

Open
Bulandent opened this issue Mar 22, 2021 · 0 comments
Open

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

Bulandent opened this issue Mar 22, 2021 · 0 comments

Comments

@Bulandent
Copy link
Owner

难度:中等
来源: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
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

1 participant