leetcode-master icon indicating copy to clipboard operation
leetcode-master copied to clipboard

这题Java版本的答案错误

Open scwlkq opened this issue 2 years ago • 1 comments

image

scwlkq avatar Oct 18 '23 07:10 scwlkq

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;
    }
}

scwlkq avatar Oct 18 '23 07:10 scwlkq