重排連結串列
阿新 • • 發佈:2021-04-04
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution:
def reorderList(self , head ):
# write code here
if not head or not head.next: return
# 快慢指標尋找中間節點
fast = head
slow = head
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
# 拆分連結串列,並將後半部分連結串列重新反轉
after = slow.next
slow.next = None
pre = None
while after:
temp = after.next
after.next = pre
pre = after
after = temp
# 交叉合併合併
first = head
after = pre
while first and after:
ftemp = first.next
atemp = after.next
first.next = after
first = ftemp
after.next = first
after = atemp