143. 重排链表

问题链接

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

解题思路

这题其实用list + 双指针模拟。很简单。 但我们要练习的是递归。

这题我本来是想用递归的方式进行模拟,但出了点问题。发现如果这样实现会有循环引用问题。

本着有简单的不用难的的原则,我开始尝试其他递归的手段。

首先分析题意,这个题目说实在的,就是将链表从中间分成两半(如果是奇数的话,左边的链表会多分一个节点),然后将第二个链表逆序,最后将2个链表的对位节点连接起来。

仔细想想,我们需要这么几个操作:

  1. 找到链表的中间节点。
  2. 将第二个链表逆序。
  3. 把两个链表连接起来。

其中,2和3可以用递归解决,1可以用快慢指针解决。

代码

class Solution:
    def reorderList(self, head) -> None:
        """
        Do not return anything, modify head in-place instead.
        """
        mid = self.search_mid(head)
        l1 = head
        l2 = mid.next
        mid.next = None
        l2 = self.reverse(l2)
        self.merge(l1, l2, l1)
  #last 代表结果链表
def merge(self, l1, l2, last): if l1 is None and l2 is None: return None if l2 is None: if last == l1: pass else: last.next = l1 return self.merge(l1.next, l2, l1) else: nxt_l1 = l1.next nxt_l2 = l2.next l2.next = l1.next l1.next = l2 return self.merge(nxt_l1, nxt_l2, l2) def reverse(self, head): if head is None or head.next is None: return head last_head = self.reverse(head.next) head.next.next = head head.next = None return last_head def search_mid(self, head): low = fast = head while fast and fast.next: low = low.next fast = fast.next.next return low

 

posted @ 2023-01-06 19:11  BJFU-VTH  阅读(25)  评论(0编辑  收藏  举报