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

python-leetcode-反转链表

方法1:迭代法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        prev, curr = None, head

        while curr:
            next_node = curr.next  # 1. 先存下一个节点
            curr.next = prev       # 2. 反转指针
            prev = curr            # 3. prev 前进
            curr = next_node       # 4. curr 前进

        return prev  # prev 成为新头部

方法 2:递归法

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, val=0, next=None):
#         self.val = val
#         self.next = next
class Solution:
    def reverseList(self, head: Optional[ListNode]) -> Optional[ListNode]:
        if not head or not head.next:
            return head  # 递归终止条件

        new_head = self.reverseList(head.next)  # 递归反转剩余部分
        head.next.next = head  # 反转当前节点指针
        head.next = None  # 断开原链

        return new_head


http://www.kler.cn/a/556871.html

相关文章:

  • 游戏引擎学习第115天
  • 力扣-二叉树-669 修剪二叉搜索树
  • 高频网络分析仪中的sdd是什么参数
  • STL介绍1:vector、pair、string、queue、map
  • Ubuntu 的RabbitMQ安装
  • 测试data_management函数
  • 网络安全:DeepSeek已经在自动的挖掘漏洞
  • 如何在 React 中测试高阶组件?
  • Windows 下如何对 node/vue 进行多版本管理?
  • Java常用设计模式及其应用场景
  • [Windows] Umi-OCR 开源批量文字识别 支持图片,文档,二维码,截图等
  • 从0-1搭建mac环境最新版
  • 常用加解密原理及实际使用
  • Vue2 和 Vue3 的区别
  • halcon激光三角测量(二十一)calibrate_sheet_of_light_calplate
  • Ubuntu24安装MongoDB(解压版)
  • 什么是向量化?ElasticSearch如何存储向量化?
  • 如何在 Vue 应用中实现权限管理?
  • 关于css中bfc的理解
  • SOME/IP--协议英文原文讲解12(完结)