每日一题 LeetCode 143. 重排链表 【双指针】【链表逆转】【链表合并】

题目链接

https://leetcode-cn.com/problems/reorder-list/

题目说明

题解

主要方法:链表找中位点;链表逆转;链表合并

解释说明:

  1. 通过双指针找链表的中位点,将链表分成两部分

    • head: L(0) -> ... -> L((n+1)//2)
    • middle: L((n+1)//2+1) -> ... -> L(n)
  2. 将后部分链表逆转

    • middle: L(n) -> ... -> L((n+1)//2+1)
  3. 将 head 和 middle 合并

    • head: L(0) -> L(n) -> L(1) -> L(n-1) -> ... -> L((n+1)//2)

代码示例:

class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not(head and head.next and head.next.next): return
        # 找中间位置
        fast, slow = head, head
        while fast.next and fast.next.next:
            fast, slow = fast.next.next, slow.next
        next_half = slow.next
        slow.next = None
        
        # 逆转
        middle = None
        while next_half:
            p, next_half = next_half, next_half.next
            p.next = middle
            middle = p
            
        # 合并
        res = head
        while middle:
            p = res.next
            res.next = middle
            middle = middle.next
            res.next.next = p
            res = p
posted @ 2020-10-20 22:44  蔺昌黎  阅读(71)  评论(0编辑  收藏  举报