定义两个指针,一个指针一次走一步,另外一个指针一次走两步,当一次走两步的指针走到终点了,那么一次走一步的指针就走到了中点。
class Solution:
"""
@param: head: the head of linked list.
@return: a middle node of the linked list.
"""
def middleNode(self, head):
if not head:
return head
slow, fast = head, head
while fast and fast.Next and fast.Next.Next:
fast = fast.next.next
slow = slow.next
return slow