# Definition for singly-linked list.# class ListNode:# def __init__(self, val=0, next=None):# self.val = val# self.next = nextclassSolution:defreorderList(self,head: Optional[ListNode]) ->None:""" Do not return anything, modify head in-place instead. """defreverse(h): pre, cur =None, hwhile cur: nxt = cur.next cur.next = pre pre = cur cur = nxtreturn predefget_mid(h): slow, fast = h, h.next # 找中间节点的前一个节点while fast and fast.next: slow = slow.next fast = fast.next.nextreturn slow mid =get_mid(head) tmp = mid.next mid.next =None# 截断 mid =reverse(tmp) l, r = head, midwhile r:# len(l) >= len(r) l_nxt, r_nxt = l.next, r.next l.next, r.next = r, l_nxt # 关键步骤: 将 r 接入 l l, r = l_nxt, r_nxt
思路2
把节点存入列表;
通过索引拼接节点;
细节:
把节点存入数组后, 可以使用下标访问节点, 形如 arr[i].next = ...
拼接节点时注意边界位置的操作;
尾节点的截断;
Python
# 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: Optional[ListNode]) -> None:
"""
Do not return anything, modify head in-place instead.
"""
tmp = []
cur = head
while cur:
tmp.append(cur)
cur = cur.next
l, r = 0, len(tmp) - 1
while l < r: # 退出循环时 l == r
tmp[l].next = tmp[r]
l += 1
if l == r: break # 易错点
tmp[r].next = tmp[l]
r -= 1
# 退出循环时 l 刚好指在中间节点(奇数时), 或中间位置的下一个节点(偶数时)
tmp[l].next = None # 易错点