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

LeetCode 19. 删除链表的倒数第N个节点 #61

Open
Chocolate1999 opened this issue Oct 4, 2020 · 0 comments
Open

LeetCode 19. 删除链表的倒数第N个节点 #61

Chocolate1999 opened this issue Oct 4, 2020 · 0 comments
Labels
双指针 双指针经典题 链表 数据结构-链表

Comments

@Chocolate1999
Copy link
Owner

仰望星空的人,不应该被嘲笑

题目描述

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

示例:

给定一个链表: 1->2->3->4->5, 和 n = 2.

当删除了倒数第二个节点后,链表变为 1->2->3->5.

说明:

给定的 n 保证是有效的。

进阶:

你能尝试使用一趟扫描实现吗?

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-nth-node-from-end-of-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

解题思路

双指针,先让一个指针q走n 步,然后另一个指针p一起走,当第一个指针q走到尾的时候,此时p指针就指向了我们要删除的节点,进行删除即可。

/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} n
 * @return {ListNode}
 */
var removeNthFromEnd = function(head, n) {
    let dummyHead = new ListNode();
    dummyHead.next = head;
    let p = dummyHead;
    let q = dummyHead;
    let k = n;
    while(k--) q = q.next; // 先让一个指针先走n步
    while(q.next){ // 一起走
        q = q.next;
        p = p.next;
    }
    p.next = p.next.next; // 找到删除节点,进行删除
    return dummyHead.next;
};

最后

文章产出不易,还望各位小伙伴们支持一波!

往期精选:

小狮子前端の笔记仓库

leetcode-javascript:LeetCode 力扣的 JavaScript 解题仓库,前端刷题路线(思维导图)

小伙伴们可以在Issues中提交自己的解题代码,🤝 欢迎Contributing,可打卡刷题,Give a ⭐️ if this project helped you!

访问超逸の博客,方便小伙伴阅读玩耍~

学如逆水行舟,不进则退
@Chocolate1999 Chocolate1999 added 链表 数据结构-链表 双指针 双指针经典题 labels Oct 4, 2020
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

1 participant