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

这题Java版本的答案错误 #2311

Open
scwlkq opened this issue Oct 18, 2023 · 1 comment
Open

这题Java版本的答案错误 #2311

scwlkq opened this issue Oct 18, 2023 · 1 comment

Comments

@scwlkq
Copy link

scwlkq commented Oct 18, 2023

image

@scwlkq
Copy link
Author

scwlkq commented Oct 18, 2023

class Solution {
   public ListNode removeNthFromEnd(ListNode head, int n){
        ListNode dummyNode = new ListNode(0);
        dummyNode.next = head;

        ListNode fastIndex = head;
        ListNode slowIndex = dummyNode;

        // 只要快慢指针相差 n 个结点即可
        for (int i = 0; i <n  ; i++){ 
            fastIndex = fastIndex.next;
        }

        while (fastIndex!= null){
            fastIndex = fastIndex.next;
            slowIndex = slowIndex.next;
        }

        //此时 slowIndex 的位置就是待删除元素的前一个位置。
        //具体情况可自己画一个链表长度为 3 的图来模拟代码来理解
        slowIndex.next = slowIndex.next.next;
        return dummyNode.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