AcWing 35. 反转链表
原题链接
简单
作者:
沙漠绿洲
,
2020-08-19 11:25:40
,
所有人可见
,
阅读 334
递归版
class Solution {
public:
// 1.递归版
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode* ret = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return ret;
}
};
迭代版
class Solution {
public:
// 2.迭代版
ListNode* reverseList(ListNode* head) {
if(!head || !head->next) return head;
ListNode *pre = nullptr, *cur = head, *ne = head->next;
while(ne){
cur->next = pre;
pre = cur;
cur = ne;
ne = ne->next;
}
cur->next = pre;
return cur;
}
};