143. 重排链表(中)

题目

  • 给定一个单链表 L 的头节点 head ,单链表 L 表示为:
    L0 → L1 → … → Ln - 1 → Ln
    请将其重新排列后变为:

    L0 → Ln → L1 → Ln - 1 → L2 → Ln - 2 → …
    不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换。

题解:双指针+翻转链表

  • 用快慢指针找到链表的中点,逆转后半截链表,此时一个指针在头,一个指针在链表中间(逆转完的第一个)交替合并两个链表即可
class Solution:
    def reorderList(self, head: Optional[ListNode]) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not head or not head.next:
            return
        # 用快慢指针找到链表的中点
        slow = head
        fast = head
        while fast and fast.next:
            slow = slow.next
            fast = fast.next.next
        # 翻转后半截链表
        prev = None
        curr = slow
        while curr:
            next_node = curr.next
            curr.next = prev#改变链表方向
            prev = curr#更新 prev
            curr = next_node#更新 curr
        # 合并前半截和翻转后的后半截链表
        p1 = head#p1在表头
        p2 = prev#p2在表中
        while p2.next:
            next_p1 = p1.next#存储p1下一个节点
            next_p2 = p2.next
            p1.next = p2#连接
            p2.next = next_p1
            p1 = next_p1#更新p1
            p2 = next_p2#更新p2
        return
posted @ 2024-01-28 14:55  Frommoon  阅读(4)  评论(0编辑  收藏  举报