当前位置: 首页 > news >正文

leetcode206. Reverse Linked List

Given the head of a singly linked list, reverse the list, and return the reversed list.
给你单链表的头节点 head ,请你反转链表,并返回反转后的链表。
输入:head = [1,2,3,4,5]
输出:[5,4,3,2,1]
思路一:双指针

class Solution:def reverseList(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:tmp = cur.next # 暂存后继节点 cur.nextcur.next = pre # 修改 next 引用指向pre = cur      # pre 暂存 curcur = tmp      # cur 访问下一节点return pre
class Solution:def reverseList(self, head: ListNode) -> ListNode:cur, pre = head, Nonewhile cur:cur.next, pre, cur = pre, cur, cur.nextreturn pre

方法二:递归

考虑使用递归法遍历链表,当越过尾节点后终止递归,在回溯时修改各节点的 next 引用指向。
recur(cur, pre) 递归函数:

终止条件:当 cur 为空,则返回尾节点 pre (即反转链表的头节点);
递归后继节点,记录返回值(即反转链表的头节点)为 res ;
修改当前节点 cur 引用指向前驱节点 pre ;
返回反转链表的头节点 res ;
class Solution:def reverseList(self, head: ListNode) -> ListNode:def recur(cur, pre):if not cur: return pre     # 终止条件res = recur(cur.next, cur) # 递归后继节点cur.next = pre             # 修改节点引用指向return res                 # 返回反转链表的头节点return recur(head, None)       # 调用递归并返回
http://www.lryc.cn/news/482465.html

相关文章:

  • 【MATLAB源码-第291期】基于matlab的AMI编码解码系统仿真,输出各个节点波形。
  • springboot苍穹外卖实战:十一:复盘总结
  • 基于Python的药房管理系统
  • chat2db数据库图形化工具
  • 弱口令整改方案:借助双因子认证加强账号密码安全
  • 动态代理的优势是什么?
  • 将大型语言模型(如GPT-4)微调用于文本续写任务
  • 引入了JUnit框架 却报错找不到:java.lang.ClassNotFoundException
  • 深度学习:tensor的定义与维度
  • 基于Python的膳食健康系统
  • FFmpeg 4.3 音视频-多路H265监控录放C++开发十三:将AVFrame转换成AVPacket。视频编码原理.编码相关api
  • 算法——移除元素(leetcode27)
  • 『OpenCV-Python』安装以及图像的读取、显示、保存
  • python开发桌面应用(跨平台) 全流程
  • el-table-column prop值根据数组获取
  • MySQL_聚合函数分组查询
  • PPT 制作神器!Markdown 轻松变幻灯片!
  • 一七八、Node.js PM2使用介绍
  • 基于CSU18M92芯片的蓝牙体重秤方案
  • 深度学习经典模型之VGGNet
  • Axure网络短剧APP端原型图,竖屏微剧视频模版40页
  • ES + SkyWalking + Spring Boot:日志分析与服务监控(三)
  • php 如何将数组转成对象数组
  • HTB:Photobomb[WriteUP]
  • 图文组合-pytorch实现
  • CentOS AppStream 8 手动更新 yum源
  • 虚拟化环境中香港服务器内存如何分配与管理?
  • Android源码中如何编译出fastboot.exe和adb.exe程序
  • C++ 参数传递 笔记
  • 【Linux】注释和配置文件的介绍