143.重排链表

难度:中等
题目描述:
在这里插入图片描述
思路总结:这题比之前做的链表题内容都丰富。需要经常回顾。首先第一种思路是递归,虽然超时了,但是思路是正确的。通过返回链表尾连接父问题的头结点,然后不断求解子问题。(len-2)
第二种思路使用了翻转链表的思想,整体分为三步,找中点,翻转后半部分,连接成一个重排链表。其中找中点利用了快慢指针,翻转链表用的是pre,cur双指针,重排链表是一个需要更新前后三个结点next的问题,还涉及到了while循环结束条件、连接前后两部分链表等细节处理。
题解一:(递归)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import functools
class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not head or not head.next or not head.next.next:return None
        @functools.lru_cache(None)
        def helper(h, ll):
            if ll == 1:
                h.next = None
                return h
            if h.next and ll == 2:
                h.next.next = None
                return h
            tail = h
            for i in range(1,ll):
                tail = tail.next
            hNext = h.next
            h.next = tail
            tail.next = helper(hNext, ll-2)
            return h
        
        h = head
        listLen = 0
        while h:
            listLen += 1
            h = h.next
        return helper(head, listLen)

题解一结果:
超时
题解二:(翻转链表思想)

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
import functools
class Solution:
    def reorderList(self, head: ListNode) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        if not head or not head.next or not head.next.next:return None
        #思路:借用翻转链表的思想,找到中点,分别翻转后半部分链表,拼接成一个链表后,交替拼接。
        fast = head
        mid = head
        while fast.next and fast.next.next:
            mid = mid.next
            fast = fast.next.next
        pre = None
        cur = mid.next
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        mid.next = pre
        h1 = head
        h2 = pre
        while h1 != mid:
            mid.next = h2.next
            h2.next = h1.next
            h1.next = h2
            h1 = h2.next
            h2 = mid.next

题解二结果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值