解题思路
代码
迭代
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 = nullptr;
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 = nullptr;
return tail;
}
};