1. 程式人生 > 實用技巧 >LeetCode 143. 重排連結串列

LeetCode 143. 重排連結串列

給定一個單鏈表 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: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if head is None or head.next is None:
            return head
        slow = head
        fast = head.next 
        while fast is not None and fast.next is not None:
            slow = slow.next
            fast = fast.next.next
        
        cur = slow.next
        slow.next = None

        mid_head = None
        while cur:
            tmp = cur.next
            cur.next = mid_head
            mid_head = cur
            cur = tmp

        p1 = head
        p2 = mid_head
        while p1 is not None and p2 is not None:
            tmp1 = p1.next
            tmp2 = p2.next
            p1.next = p2
            p2.next = tmp1
            p1 = tmp1
            p2 = tmp2