题解:链表反转,递归和非递归两种写法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseList(ListNode* head) {
return REList(head,nullptr);
}
ListNode* REList(ListNode* head, ListNode* prev = nullptr){
if(!head){
return prev;
}
ListNode *next = head->next;
head->next = prev;
return REList(next,head);
}
};
class Solution {
public:
ListNode* reverseList(ListNode* head) {
ListNode* root = nullptr;
ListNode* h;
while(head){
h = head->next;
head->next = root;
root = head;
head = h;
}
return root;
}
};