要回傳 Linked List 中間的節點,如果長度是偶數,則中間偏右那一個。
有兩種解法:
第一種是跑完一遍得到長度,計算距離,再從頭跑到中間即可。前進距離是 length //2 。
第二種是用快慢指針,每回合快針走兩步,慢針走一步。當到了快針不能再走的回合,慢針會在中間的位置。
class Solution:
def middleNode(self, head: ListNode) -> ListNode:
if not head: return head
FP, SP = head, head
while FP and FP.next:
FP = FP.next.next
SP = SP.next
return SP