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
相关推荐
北顾笙9804 分钟前
day22-数据结构力扣
数据结构·算法·leetcode
人道领域10 分钟前
【LeetCode刷题日记】454:四数相加Ⅱ
算法·leetcode
进击的荆棘1 小时前
递归、搜索与回溯——递归
算法·leetcode·递归
小白菜又菜11 小时前
Leetcode 2075. Decode the Slanted Ciphertext
算法·leetcode·职场和发展
摸个小yu15 小时前
【力扣LeetCode热题h100】链表、二叉树
算法·leetcode·链表
skywalker_1117 小时前
力扣hot100-5(盛最多水的容器),6(三数之和)
算法·leetcode·职场和发展
生信研究猿17 小时前
leetcode 226.翻转二叉树
算法·leetcode·职场和发展
XWalnut17 小时前
LeetCode刷题 day9
java·算法·leetcode
6Hzlia18 小时前
【Hot 100 刷题计划】 LeetCode 39. 组合总和 | C++ 回溯算法与 startIndex 剪枝
c++·算法·leetcode
宵时待雨18 小时前
优选算法专题1:双指针
数据结构·c++·笔记·算法·leetcode