首页 > 其他分享 >143. 重排链表

143. 重排链表

时间:2023-01-06 19:23:34浏览次数:44  
标签:head 143 self l1 next 链表 l2 重排

问题链接

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

 

标签:head,143,self,l1,next,链表,l2,重排
From: https://www.cnblogs.com/bjfu-vth/p/17031414.html

相关文章

  • 基于单链表的学生管理系统
    基于单链表的学生管理系统(Student-Management-System)学生管理系统(Student-Management-System)项目链接:https://github.com/caojun97/Student-Management-System一、......
  • 24. 两两交换链表中的结点
    题目链接https://leetcode.cn/problems/swap-nodes-in-pairs/description/解题思路首先这是个递归问题,因为它可以明显的缩小问题规模。既然是递归的问题,那我们按照递归......
  • 链表
    1.什么是链表链表(LinkedList):一种线性表数据结构。它使用一组任意的存储单元(可以是连续的,也可以是不连续的),来存储一组具有相同类型的数据。即「链表」是实现线性表......
  • list双链表
    structlistnode{structlistnode*next;structlistnode*prev;void*data;};structlist_head{ structlist_head*next,*prev;};/*Linkedlistof......
  • 静态链表
    以下是链表的相关实现函数单链表//head存储链表头,e[]存储节点的值,ne[]存储节点的next指针,idx表示当前用到了哪个节点inthead,e[N],ne[N],idx;//初始化voidin......
  • upload.html:143 GET http://localhost:8080/user_image/85F250A6-E07D-4FCB-8092-D4A
    publicclassLoginInterceptorConfigureimplementsWebMvcConfigurer{@OverridepublicvoidaddResourceHandlers(ResourceHandlerRegistryregistry){......
  • python 删除链表倒数第n个节点
    defdelete_k_node(self,head,index):"""删除链表倒数第k个节点:paramhead::paramindex::return:"""......
  • C++实现有序表--链表的合并操作代码
    #include<iostream>#include<cstdlib>usingnamespacestd;#defineMAXSIZE100#defineOK1#defineERROR0typedefintElemtype;typedefintStatus;typedefstructLNo......
  • 单链表
    单链表typedefstructLNode{ElemTypedata;structLNode*next;}LNode,*LinkList1.不带头结点boolInitList(LinkList&L){L=NULL;returntr......
  • Leetcode 重排链表 递归
    https://leetcode.com/problems/reorder-list/solutions/45113/Share-a-consise-recursive-solution-in-C++/https://leetcode.cn/problems/reorder-list/solutions/32910......