AcWing 35. 反转链表
原题链接
简单
作者:
Bear_King
,
2021-03-19 20:36:57
,
所有人可见
,
阅读 285
迭代版本
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;
}
};
递归版本
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;
}
};