leetcode 206反转链表

cpp 复制代码
/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* reverseList(ListNode* head) {
        ListNode *pre = nullptr;
        ListNode *cur = head;
        while(cur !=nullptr){
            ListNode *next = cur->next;
            cur->next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
};

这题是反转单链表,核心用三个指针:

复制代码
pre   // 前一个节点
cur   // 当前节点
next  // 下一个节点

核心四步:

复制代码
ListNode *next = cur->next; // 1. 保存下一个
cur->next = pre;            // 2. 当前指针反转
pre = cur;                  // 3. pre 前进
cur = next;                 // 4. cur 前进

一句话记忆:

保存后面 → 指针反转 → pre 前进 → cur 前进

最容易错的点是最后:

复制代码
return pre;

不能写:

复制代码
return cur;

因为循环结束时:

复制代码
cur == nullptr

而 pre 才指向反转后链表的新头节点。

例如:

复制代码
1 → 2 → 3 → nullptr

反转后:

复制代码
3 → 2 → 1 → nullptr

复杂度:

\ \\boxed{时间复杂度 O(n)} \\\ \\boxed{空间复杂度 O(1)} \\

相关推荐
文丑颜不良啊1 小时前
LeetCode2241~2260题目解析
java·leetcode
文丑颜不良啊1 小时前
LeetCode2321~2340题目解析
java·leetcode
青少儿编程课堂1 小时前
蓝桥杯青少组图形化 STEMA 省考(报名倒计时·11/22开考)+ 全国青少年信息素养大赛 2026—2027赛季 + 电子学会图形化考级:校园华容道大闯关
c++·python·算法·bfs·信息学竞赛
在猴站学算法2 小时前
(《统计学习方法》(第2版) 李航)第2章 感知机算法
学习·算法·机器学习·统计学习
Rainmicro2 小时前
【无标题】
java·数据库·算法
NEFU_Jyj12 小时前
牛客周赛R168
算法
文丑颜不良啊20 小时前
LeetCode2221~2240题目解析
java·leetcode
Navigator_Z20 小时前
LeetCode //C - 1317. Convert Integer to the Sum of Two No-Zero Integers
c语言·算法·leetcode