递归版
class Solution {
public:
ListNode* reverseList(ListNode* head) {
if(head==nullptr||head->next==nullptr) return head;
auto node=reverseList(head->next);
head->next->next=head;
head->next=nullptr;
return node;
}
};
迭代版
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* pre=nullptr;
while(head!=nullptr)
{
auto t=head->next;
head->next=pre;
pre=head;
head=t;
}
return pre;
}
};
Q.E.D.