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

倒数第K个节点 #52

Open
fnlearner opened this issue Oct 11, 2019 · 1 comment
Open

倒数第K个节点 #52

fnlearner opened this issue Oct 11, 2019 · 1 comment

Comments

@fnlearner
Copy link
Contributor

设置一个头结点,它的下一个节点是原始指针,设置两个指针,一个快指针,一个慢指针,快指针多走n+1步,这样当快指针到达尾部的下一个节点的时候,慢指针的下一个节点就是要删除的节点

var removeNthFromEnd = function(head, n) {
    let dummy = new ListNode(0);
    dummy.next= head;
    let slow =dummy;
    let fast = dummy;
    while(n>=0){
        fast = fast.next;
        n--;
    }
    if(!fast) return head.next;
    while(fast!=null){
        fast = fast.next;
        slow = slow.next;
    }  
    slow.next = slow.next.next; 
    return dummy.next;

};
@wangbojing
Copy link
Member

commit to master.

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

2 participants