143. 重排連結串列(中等,鏈)(12.25)
阿新 • • 發佈:2019-01-05
給定一個單鏈表 L:L0→L1→…→Ln-1→Ln ,
將其重新排列後變為: L0→Ln→L1→Ln-1→L2→Ln-2→…
你不能只是單純的改變節點內部的值,而是需要實際的進行節點交換。
示例 1:
給定連結串列 1->2->3->4, 重新排列為 1->4->2->3.
示例 2:
給定連結串列 1->2->3->4->5, 重新排列為 1->5->2->4->3.
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def reorderList(self, head): """ :type head: ListNode :rtype: void Do not return anything, modify head in-place instead. """ if not head: return None slow=head fast=head while fast and fast.next: slow=slow.next fast=fast.next.next head1=head head2=slow.next slow.next = None #不是很清楚這句話的意思 #反轉第二條鏈 cur, pre = head2, None while cur: nex = cur.next cur.next = pre pre = cur cur = nex #交叉 cur1, cur2 = head1, pre while cur2: nex1, nex2 = cur1.next, cur2.next cur1.next = cur2 cur2.next = nex1 cur1, cur2 = nex1, nex2
執行用時: 116 ms, 在Reorder List的Python3提交中擊敗了95.60% 的使用者