143. 重排連結串列

WrRan發表於2024-09-12
題目連結 143. 重排連結串列
思路 連結串列綜合題:快慢指標(找連結串列一半位置)+ 連結串列翻轉
題解連結 【影片】沒想明白?一個影片講透!(Python/Java/C++/Go/JS)
關鍵點 快慢指標:while fast and fast.next: ... && 合併時結束條件:while second.next: ...
時間複雜度 \(O(n)\)
空間複雜度 \(O(1)\)

程式碼實現:

class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        second = self.halfList(head)
        second = self.reverseList(second)
        
        while second.next:
            next_node_1 = head.next
            next_node_2 = second.next
            head.next = second
            second.next = next_node_1
            head = next_node_1
            second = next_node_2
        
    def halfList(self, head):
        slow = fast = head
        while fast and fast.next:
            fast = fast.next.next
            slow = slow.next
        return slow
    
    def reverseList(self, head):
        previous = None
        current = head
        while current:
            next_node = current.next
            current.next = previous
            previous = current
            current = next_node
        return previous

相關文章