1. 程式人生 > >【LeetCode 中等題】66-重排連結串列

【LeetCode 中等題】66-重排連結串列

題目描述:給定一個單鏈表 LL0→L1→…→Ln-1→Ln ,將其重新排列後變為: L0→LnL1→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.

解法1。方法就是找到連結串列中間節點,斷開成兩段,把後半段逆轉,然後再兩個連結串列合併,互相改變next指標,如下

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if not head or not head.next:
            return

        # 找到中間節點,切斷
        slow = head
        fast = slow.next
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        mid = slow.next
        slow.next = None
        
        # 逆轉連結串列
        pre = None
        cur = mid
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        
        # 前後兩段連結串列合併
        head1 = head
        head2 = pre
        while head1 and head2:
            tmp = head2.next
            head2.next = head1.next
            head1.next = head2
            head1 = head1.next.next
            head2 = tmp