AcWing 35. 反转链表
原题链接
简单
作者:
白眉
,
2025-01-15 23:21:05
,
所有人可见
,
阅读 1
迭代版
/**
* 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 p = head, q = p->next;
while(q){
auto o = q->next;
q->next = p;
p=q,q=o;
}
head->next = NULL;
return p;
}
};
递归版
/**
* 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;
if(head==NULL || head->next==NULL) return head;
ListNode* res = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return res;
}
};