Middle of Linked List
- 1 min read
- LC-Easy
- Linked List
Solution
- Same as Middle Node
- Slow and fast pointers
- Move fast twice as fast i.e. two nodes at a time, and move slow one node at a time
- When fast or fast.next reaches null, slow is at middle, return slow
| Time | Space | Explanation |
|---|
O(n) | O(n) | |
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow