LeetCode Reorder List

LeetCode解題之Reorder List


原題

將單向鏈表L0→L1→…→Ln-1→Ln轉化爲L0→Ln→L1→Ln-1→L2→Ln-2→…的形式,也就是從頭部取一個節點,從尾部取一個節點,直到將原鏈表轉化成新的鏈表。

注意點:

  • 不要申請額外的空間
  • 不要修改節點的數值

例子:

輸入: {1,2,3,4}

輸出: {1,4,2,3}

解題思路

由於是一個單向鏈表,從尾部不斷取元素比較困難,所以我們要將鏈表反轉,又因爲是同時從兩頭取元素,所以我們只需要反轉後半段鏈表。我們先通過快慢指針來獲得鏈表的中間節點,並將鏈表截斷。接着翻轉後半段鏈表,最後依次從兩個鏈表中提取元素進行連接。需要注意的是,在截斷時注意哪個鏈表比較長,合併的時候不要遺漏元素。

AC源碼

class Solution(object):
    def reorderList(self, head):
        """
        :type head: ListNode
        :rtype: void Do not return anything, modify head in-place instead.
        """
        if not head:
            return
        # split
        fast = slow = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        head1, head2 = head, slow.next
        slow.next = None
        # reverse
        cur, pre = head2, None
        while cur:
            nex = cur.next
            cur.next = pre
            pre = cur
            cur = nex
        # merge
        cur1, cur2 = head1, pre
        while cur2:
            nex1, nex2 = cur1.next, cur2.next
            cur1.next = cur2
            cur2.next = nex1
            cur1, cur2 = nex1, nex2


if __name__ == "__main__":
    None

歡迎查看我的Github (https://github.com/gavinfish/LeetCode-Python) 來獲得相關源碼。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章