LeetCode 143. 重排鏈表 reorder list Python3解法

# 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 and head.next and head.next.next:
            # 找中點
            p_slow, p_fast = head, head
            while p_fast and p_fast.next:
                p_slow = p_slow.next
                p_fast = p_fast.next.next
            # 後半部分逆序
            p_bh_pre = p_slow.next
            p_slow.next = None
            p_bh_cur = p_bh_pre.next
            node = ListNode(0)
            node.next = p_bh_pre
            while p_bh_cur:
                p_bh_pre.next = p_bh_cur.next
                p_bh_cur.next = node.next
                node.next = p_bh_cur
                p_bh_cur = p_bh_pre.next
            # 插入
            p_qian, p_hou = head, node.next
            while p_qian and p_hou:
            	# 先保留先半部分的下一個節點
                node.next = p_qian.next
                # 插入後半部分的第一個節點
                p_qian.next = p_hou
                # 後半部分後移
                p_hou = p_hou.next
                # 插入後改變next
                p_qian.next.next = node.next
                p_qian = node.next
            
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章