classSolution:defmiddleNode(self, head: Optional[ListNode])-> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextreturn slow
classSolution:defhasCycle(self, head: Optional[ListNode])->bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextif slow is fast:returnTruereturnFalse
classSolution:defdetectCycle(self, head: Optional[ListNode])-> Optional[ListNode]:
fast = slow = head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextif fast is slow:while slow isnot head:
slow = slow.next
head = head.nextreturn slow
returnNone
classSolution:defmiddleNode(self, head: Optional[ListNode])->Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.nextreturn slow
defreverseList(self, head: Optional[ListNode])->Optional[ListNode]:
pre, cur =None, head
while cur:
nxt = cur.next
cur.next= pre
pre = cur
cur = nxt
return pre
defreorderList(self, head: Optional[ListNode])->None:
mid = self.middleNode(head)
head2 = self.reverseList(mid)while head2.next:
nxt = head.next
nxt2 = head2.next
head.next= head2
head2.next= nxt
head = nxt
head2 = nxt2