143. 重排链表

题目链接 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
posted @ 2024-09-12 00:43  WrRan  阅读(4)  评论(0编辑  收藏  举报