LeetCode/NeetCode
[Linked Lists: Fast and Slow Pointers] 876. Middle of the Linked List
hyunkookim
2025. 4. 6. 03:34
876. Middle of the Linked List
# Definition for singly-linked list.
# 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는 두 칸씩 이동
- fast가 끝에 도달하면, slow는 중간에 도달
"""
slow = fast = head
#while fast.next.next: <-- 안됨
while fast and fast.next:
# while fast and fast.next: 는 다음 조건 만족
# fast가 None이 아닌지 확인
# fast.next가 존재하는지 확인 → 그러고 나서 fast.next.next 접근
slow = slow.next
fast = fast.next.next
return slow