/**
* 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) {
if (!head || !head->next) {
return head;
}
ListNode* newHead = reverseList(head->next);
head->next->next = head;
head->next = nullptr;
return newHead;
}
};
/*
递归原理:
以反转1 2 3 4 5为例
nullptr
1 2 3 4 5 ⬆
⬆ newHead(1) = newHead(2) = head(5) 1⬅2⬅3⬅4⬅5
head(1) head(1)->next->next = head(1) 即 head(2)->next = head(1) ⬆
head(1)->next = nullptr newHead
return newHead(1) = head(5)
⬆ nullptr
1 2 3 4 5 ⬆
⬆ newHead(2) = newHead(3) = head(5) 1➡2⬅3⬅4⬅5
head(2) head(2)->next->next = head(2) 即 head(3)->next = head(2) ⬆
head(2)->next = nullptr newHead
return newHead(2) = head(5)
⬆ nullptr
1 2 3 4 5 ⬆
⬆ newHead(3) = newHead(4) = head(5) 1➡2➡3⬅4⬅5
head(3) head(3)->next->next = head(3) 即 head(4)->next = head(3) ⬆
head(3)->next = nullptr newHead
return newHead(3) = head(5)
⬆ nullptr
1 2 3 4 5 ⬆
⬆ ➡ newHead(4) = head(5) 1➡2➡3➡4⬅5
head(4) head(4)->next->next = head(4) 即 head(5)->next = head(4) ⬆
head(4)->next = nullptr newHead
return newHead(4) = head(5)
⬆ nullptr
1 2 3 4 5 ⬆
⬆ ➡ head->next = nullptr 1➡2➡3➡4➡5
head(5) return head(5) ⬆
newHead
*/
09-14
261
09-14
323