参考解析
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def reorderList(self, head: ListNode) -> None:
"""
Do not return anything, modify head in-place instead.
"""
if not head:
return head
mid = self.findMid(head)
tail = self.reverseList(mid.next)
mid.next = None
dummy = ListNode()
dummy.next = head
cur = dummy
while head and tail:
cur.next = head
cur = cur.next
head = head.next
cur.next = tail
cur = cur.next
tail = tail.next
if head:
cur.next = head
return dummy.next
def findMid(self, head):
slow = fast = head
while fast and fast.next:
slow = slow.next
fast = fast.next.next
return slow
def reverseList(self, head):
pre, cur = None, head
while cur:
cur.next, pre, cur = pre, cur, cur.next
return pre