AcWing 35. 反转链表
原题链接
简单
作者:
回归线
,
2021-03-27 20:27:48
,
所有人可见
,
阅读 250
迭代
/**
* 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;
auto b = a->next;
while (b) {
auto c = b->next;
b->next = a;
a = b;
b = c;
}
head->next = nullptr;
return 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 a = head->next;
auto b = reverseList(a);
a->next = head;
head->next = nullptr;
return b;
}
};
写反了
哈哈,是的,我来改一下