快慢指针
链表的快慢指针和数组的双指针或者相向双指针都是解决各自问题最基本的套路。
一、876. 链表的中间结点

- 代码:
python
class Solution:
def middleNode(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
二、141. 环形链表

- 代码:
python
class Solution:
def hasCycle(self, head: Optional[ListNode]) -> bool:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast == slow:
return True
return False
三、142. 环形链表 II

- 代码:
python
class Solution:
def detectCycle(self, head: Optional[ListNode]) -> Optional[ListNode]:
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
if slow is fast:
cur = head
while cur != fast:
cur = cur.next
fast = fast.next
return cur
return None
四、143. 重排链表

- 代码:
python
def middleNode(head):
slow = head
fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def reverseList(head):
pre = None
cur = head
while cur:
nxt = cur.next
cur.next = pre
pre = cur
cur = nxt
return pre
class Solution:
def reorderList(self, head: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
mid = middleNode(head)
head2 = reverseList(mid)
while head2.next:
nxt = head.next
nxt2 = head2.next
head.next = head2
head2.next = nxt
head = nxt
head2 = nxt2