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
相关推荐
参.商.2 小时前
【Day41】143. 重排链表
leetcode·golang
Zaly.5 小时前
【Python刷题】LeetCode 1727 重新排列后的最大子矩阵
算法·leetcode·矩阵
memcpy07 小时前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
玛丽莲茼蒿7 小时前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
wen__xvn8 小时前
力扣模拟题刷题
算法·leetcode
不要秃头的小孩8 小时前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
We་ct8 小时前
LeetCode 35. 搜索插入位置:二分查找的经典应用
前端·算法·leetcode·typescript·个人开发
Navigator_Z9 小时前
LeetCode //C - 990. Satisfiability of Equality Equations
c语言·算法·leetcode
lightqjx10 小时前
【算法】前缀和
c++·算法·leetcode·前缀和
窝子面10 小时前
LeetCode练题三:链表
算法·leetcode·链表