
迭代版本
点击查看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
auto a = head, b = a->next;
while (b) {
auto c = b->next;
b->next = a;
a = b, b = c;
}
head->next = NULL;
return a;
}
};
- 当是空链表或只有一个结点时,直接返回头结点 head;
- 当 b 不为空时,a 指向当前结点 p,b 指向 p->next,c 指向 p->next->next,每次将 b->next = a,并移动指针 a = b, b = c;
- head 此时指向的是新链表的尾结点,head->next = NULL;
- 新链表的头结点是 a;
递归版本
点击查看代码
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if (!head || !head->next) return head;
auto tail = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return tail;
}
};
- 当是空链表或只有一个结点时,直接返回头结点 head;
- 递归调用 reverseList(head->next),最后一次递归,反转链表尾结点为 head->next,head->next->next = NULL,此时执行 head->next->next = head 对 head 结点进行反转,head 变为新的反转链表的尾结点,head->next = NULL;
- 返回的 tail 是反转链表的头结点;
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· 没有Manus邀请码?试试免邀请码的MGX或者开源的OpenManus吧
· 【自荐】一款简洁、开源的在线白板工具 Drawnix
· 园子的第一款AI主题卫衣上架——"HELLO! HOW CAN I ASSIST YOU TODAY
· Docker 太简单,K8s 太复杂?w7panel 让容器管理更轻松!