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

如何使用 Python 实现链表的反转?

在Python中实现链表的反转可以通过几种不同的方法。这里,我将向你展示如何使用迭代和递归两种方式来反转链表。
1. 迭代方法
迭代方法是通过遍历链表,逐个节点地改变其指向来实现反转的。
class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next

def reverseList(head):
    prev = None
    current = head
    while current:
        next_node = current.next
        current.next = prev
        prev = current
        current = next_node
    return prev

# 示例使用
# 创建链表 1 -> 2 -> 3 -> None
head = ListNode(1, ListNode(2, ListNode(3)))
# 反转链表
reversed_head = reverseList(head)
# 打印反转后的链表
while reversed_head:
    print(reversed_head.val, end=" -> ")
    reversed_head = reversed_head.next

2. 递归方法
递归方法是通过递归调用来反转链表,每次递归反转一个节点,直到链表的末尾。
def reverseListRecursive(head):
    if not head or not head.next:
        return head
    new_head = reverseListRecursive(head.next)
    head.next.next = head
    head.next = None
    return new_head

# 示例使用
# 创建链表 1 -> 2 -> 3 -> None
head = ListNode(1, ListNode(2, ListNode(3)))
# 反转链表
reversed_head = reverseListRecursive(head)
# 打印反转后的链表
while reversed_head:
    print(reversed_head.val, end=" -> ")
    reversed_head = reversed_head.next

这两种方法都可以有效地反转链表,选择哪种方法取决于你的偏好和具体的应用场景。迭代方法通常更节省空间,因为它不需要额外的栈空间,而递归方法在代码上更为简洁,但需要注意递归深度的问题。

http://www.lryc.cn/news/499817.html

相关文章:

  • react跳转传参的方法
  • Scala:正则表达式
  • 【数电】常见时序逻辑电路设计和分析
  • Spring IOCAOP
  • Scala中的隐式转换
  • GESP 2024年12月认证 真题 及答案
  • C++多态性
  • PyODBC: Python 与数据库连接的桥梁
  • 专题二十五_动态规划_两个数组的 dp (含字符串数组)_算法专题详细总结
  • PHP语法学习(第七天)-循环语句,魔术常量
  • 数据库授权讲解一下
  • 组件开发的环境准备: nodejs安装,npm镜像源的修改,pnpm包管理器的安装(全局安装),基于pnpm创建脚手架项目
  • 学生成绩统计系统
  • 【Spring项目】图书管理系统
  • Vivado ILA数据导出MATLAB分析
  • 【开源免费】基于SpringBoot+Vue.JS高校学科竞赛平台(JAVA毕业设计)
  • 【机器学习】——windows下安装anaconda并在vscode上进行配置
  • 【H2O2|全栈】Node.js与MySQL连接
  • 汽配行业数字化解决方案(一)
  • 前端路径“@/“的使用和配置
  • 动态规划子序列问题系列一>最长递增子序列
  • 链表头文件大更新!!!
  • 力扣3381.长度可被K整除的子数组的最大元素和
  • http.ServeMux多路复用器的设置
  • 优化器与优化方法:在现代科学与工程中的应用
  • 笔记本外接显示屏没声音
  • vue框架
  • Vue指令(一)--v-html、v-show、v-if、v-else、v-else-if、v-on、v-bind、v-for、v-model
  • ElK 8 收集 MySQL 慢查询日志并通过 ElastAlert2 告警至飞书
  • QT通过在线安装器安装【详细】