class Solution: def removeNthFromEnd(self, head: Optional[ListNode], n: int) -> Optional[ListNode]: slow, fast = head, head # fast 先走 n 步 for _ in range(n): fast = fast.next # 如果 fast 走到 None,说明删除的是头节点 if not fast: return head.next # 同步移动,直到 fast 到最后一个节点 while fast.next: slow = slow.next fast = fast.next # 删除 slow.next 节点 slow.next = slow.next.next return head
class Solution: def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]: slow, fast = head, head while fast and fast.next: slow = slow.next fast = fast.next.next return slow