vault backup: 2022-09-20 13:28:10
This commit is contained in:
parent
2f2e8488d3
commit
b375b417c1
|
@ -122,17 +122,32 @@ public:
|
|||
|
||||
Recursion:
|
||||
|
||||
2022-09-20 version
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
ListNode *reverseList(ListNode *head) {
|
||||
// Recursion
|
||||
|
||||
// Base case: no need to reverse:
|
||||
if (head == nullptr || head->next == nullptr) {
|
||||
return head;
|
||||
}
|
||||
|
||||
// assuming we have the head of reversed sub-list
|
||||
// head->next still points to next one in the unchanged order,
|
||||
// or the tail of the reversed list
|
||||
auto newHead = reverseList(head->next);
|
||||
|
||||
head->next->next = head;
|
||||
head->next = nullptr;
|
||||
|
||||
return newHead;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
```cpp
|
||||
/**
|
||||
* 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) {
|
||||
|
|
Loading…
Reference in a new issue