給定一個 linked list head,回傳中間的 node
如果是偶數個,回傳靠近尾部的
這題可以使用快慢指針法求解
需要注意的是雙數與單數要分開運算
# 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]:
f, s = head, head
while True:
if not f.next:
return s
if not f.next.next:
return s.next
s = s.next
f = f.next.next