题目

Remove Nth Node From End of List

题解

双指针技巧是常见的处理链表的手法,这里我们运用其中的快慢指针方法来解题:首先让一个快指针从head开始提前移动k个节点,然后把慢指针初始化为head,再让两个指针同时前进。当快指针到达链表末尾的Null时,慢指针就会指向倒数第k个节点。

代码

class Solution:
    def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]:
        forward_node = head
        count = 0
        while forward_node is not None and count < n:
            forward_node = forward_node.next
            count += 1

        previous = None
        current = head
        while forward_node is not None:
            previous = current
            current = current.next
            forward_node = forward_node.next

        if previous is None:
            head = head.next
        else:
            previous.next = current.next

        return head