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
相关推荐
Navigator_Z1 天前
LeetCode //C - 1031. Maximum Sum of Two Non-Overlapping Subarrays
c语言·算法·leetcode
如何原谅奋力过但无声1 天前
【灵神高频面试题合集01-03】相向双指针、滑动窗口
数据结构·python·算法·leetcode
leoufung1 天前
LeetCode 42:接雨水 —— 从“矩形法”到双指针的完整思考过程
java·算法·leetcode
_日拱一卒1 天前
LeetCode:543二叉树的直径
算法·leetcode·职场和发展
穿条秋裤到处跑1 天前
每日一道leetcode(2026.04.28):获取单值网格的最小操作数
算法·leetcode·职场和发展
leoufung1 天前
LeetCode 68. Text Justification 题解:贪心与实现细节
算法·leetcode·职场和发展
洛水水1 天前
【力扣100题】17.K 个一组翻转链表
算法·leetcode·链表
洛水水1 天前
【力扣100题】16.两两交换链表中的节点
算法·leetcode·链表
leoufung1 天前
LeetCode 30:Substring with Concatenation of All Words 题解(含 C 语言 uthash 实现)
c语言·leetcode·c#
样例过了就是过了1 天前
LeetCode热题100 最小路径和
c++·算法·leetcode·动态规划