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)} \\