Solution 1 - Slow & Fast Pointers
Fast moves 2 steps, slow moves 1 step. When fast ends, slow is at the middle (second middle for even length).
Fast moves 2 steps, slow moves 1 step. When fast ends, slow is at the middle (second middle for even length).
""" 0876.1 - Middle of the Linked List - Solution 1 - Slow & Fast Pointers """
from typing import Optional
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class Solution:
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