題目連結 | 876. 連結串列的中間結點 |
---|---|
思路 | 快慢指標-經典應用題 |
題解連結 | 沒想明白?一個影片講透!(Python/Java/C++/Go/JS/Rust) |
關鍵點 | while fast and fast.next: ... |
時間複雜度 | \(O(n)\) |
空間複雜度 | \(O(1)\) |
程式碼實現:
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
fast = fast.next.next
slow = slow.next
return slow