反転チェーンテーブル-再帰実装leetcode 206
766 ワード
/**
* 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==nullptr||head->next==nullptr){
return head;
}
ListNode *save = reverse(head->next,head);
head->next=nullptr;
return save;
}
ListNode *reverse(ListNode *root, ListNode *last) {
ListNode *n;
if (root->next == nullptr) {
root->next = last;
return root;
} else {
n = reverse(root->next, last->next);
root->next = last;
return n;
}
return nullptr;
}
};