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
相关推荐
_日拱一卒8 小时前
LeetCode:437路径总和Ⅲ
算法·leetcode·职场和发展
世纪末的小黑8 小时前
【LeetCode自用】LeetCode自用记录贴,题目一:两数之和
数据结构·算法·leetcode
兰令水8 小时前
topcode【随机算法题】【2026.5.22打卡-java版本】
java·算法·leetcode
水木流年追梦21 小时前
大模型入门-Reward 奖励模型训练
开发语言·python·算法·leetcode·正则表达式
始三角龙1 天前
LeetCode hoot 100 -- 缺失的第一个正整数
算法·leetcode·职场和发展
战南诚1 天前
力扣 之 198.打家劫舍
python·算法·leetcode
_日拱一卒1 天前
LeetCode:105从前序与中序遍历序列构造二叉树
算法·leetcode·职场和发展
ʚ希希ɞ ྀ1 天前
dp反思与总结
算法·leetcode·动态规划
菜菜的顾清寒1 天前
力扣Hot100(23)反转链表
算法·leetcode·链表
m0_629494731 天前
LeetCode 热题 100-----27. 合并两个有序链表
数据结构·算法·leetcode·链表