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个节点 #11

Open
louzhedong opened this issue Apr 26, 2018 · 0 comments
Open

删除链表的倒数第N个节点 #11

louzhedong opened this issue Apr 26, 2018 · 0 comments

Comments

@louzhedong
Copy link
Owner

题目

出处:LeetCode 算法第19题

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

示例:

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

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

说明:

给定的 n 保证是有效的。

进阶:

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

思路

由于只能实现一遍扫描,所以我们可以使用两个指针,让一个指针先走一定的步数,使两个指针之间间隔n步,当前面的指针移动到链表尾部的时候,后面的指针刚好处于要删除的节点的前面,将它的next指向next.next就可以了。为了处理删除第一个节点的情况,我们在链表头部新建一个节点,使其指向第一个节点。

实现

var removeNthFromEnd = function(head, n) {
    var result = new ListNode(0);
    result.next = head;
    var second = result;
    while(n > 1) {
        head = head.next;
        n--;
    }
    while(head.next != null) {
        head = head.next;
        second = second.next;
    } 
    second.next = second.next.next;
    return result.next;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant