leetcode hot100 206.反转链表 easy


在遍历的过程中,改变每个节点的 next 指针,让它指向它的前驱节点。

由于单链表没有指向前驱的指针,我们需要在遍历时手动维护一个 prev 变量。

时间复杂度:O(n)O(n)O(n)

空间复杂度:O(1)O(1)O(1)

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]:
        
        if not head:
            return None

        pre = None   # 头节点前面的设一个空节点,先不用指向头节点,因为但反过来之后,头节点就指向none
        cur = head

        while cur:
            tmp = cur.next # 暂存后继节点 cur.next
            cur.next = pre  # 修改 next 引用指向
            pre  = cur
            cur = tmp

        return pre
相关推荐
hanlin033 小时前
刷题笔记:力扣第32题-最长有效括号
笔记·算法·leetcode
All for pursuit.3 小时前
【动态规划-21】312.戳气球
数据结构·c++·算法·leetcode·动态规划
Scintilla_y6 小时前
DAY2 滑动窗口
算法·leetcode·散列表
特立独行的猫a7 小时前
仓颉语言UI开发实战:我用仓颉写了个桌面版力扣
算法·leetcode·ui·tauri·仓颉·cj-tarui
y1su7 小时前
Leetcode 动态规划 模板
java·数据结构·算法·leetcode·动态规划
All for pursuit.8 小时前
【位运算-3】136.只出现一次的数字
数据结构·c++·算法·leetcode
All for pursuit.10 小时前
【完结】LeetCodeHot100题 详细解题过程及代码汇总
数据结构·c++·算法·leetcode
mmmmath_310 小时前
LeetCode.101.对称二叉树
数据结构·leetcode
mmmmath_315 小时前
LeetCode.637.二叉树的层平均值
算法·leetcode
Tisfy15 小时前
LeetCode 2913.子数组不同元素数目的平方和 I:第一题先常数很大的O(n^2)
算法·leetcode·题解·模拟·暴力