LeetCode热题100-反转链表

python3实现

  • 循环方法:设置双指针,空间复杂度1,时间复杂度n
python 复制代码
# 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]:
        cur, pre = head, None
        while cur:
            tmp = cur.next
            cur.next = pre
            pre = cur
            cur = tmp
        return pre

这里返回的pre,因为结束循环的条件为cur为空,当cur为空时,pre正好为表头。

  • 递归:注意递归设置的条件,第一次返回的表头
python 复制代码
# 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]:
        def recur(cur, pre):
            if not cur:
                return pre
            res = recur(cur.next, cur)
            cur.next = pre
            return res
        
        return recur(head, None)
相关推荐
Forever Nore1 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
北斗落凡尘2 小时前
LangGraph 入门实战(2)
python·langchain
ttod_qzstudio2 小时前
Java 常用语法极简通关(五):类与对象——字段、方法、构造器、this 与 static
java·开发语言·python
jufeng13073 小时前
【系列:手搓自主 AI Agent:Hermes 架构原理剖析 · 第 1 篇】
人工智能·python·架构·agent
月光船幽幽4 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
_oP_i6 小时前
python 后缀 mjs文件
开发语言·python
北斗落凡尘6 小时前
如何使用LangGraph(1)
python·langchain
Livia要学习8 小时前
Python装饰器
开发语言·python
evans在进步8 小时前
LeetCode 200:岛屿数量——Java DFS 染色法详解
java·leetcode·深度优先
大模型丫丫9 小时前
LangChain4j:Java 生态的 AI 应用开发利器
java·人工智能·python