vault backup: 2022-07-02 08:27:19
This commit is contained in:
parent
726dc67f4a
commit
ee1e87b6af
|
@ -75,8 +75,7 @@ The in place insert is easier to understand, and simple to implement, using a ve
|
||||||
### Solution
|
### Solution
|
||||||
I've referred to this guy: https://leetcode.com/problems/reverse-linked-list/discuss/58130/C%2B%2B-Iterative-and-Recursive
|
I've referred to this guy: https://leetcode.com/problems/reverse-linked-list/discuss/58130/C%2B%2B-Iterative-and-Recursive
|
||||||
|
|
||||||
This code is hard to understand.
|
Insertion, iteration
|
||||||
==TODO==: Make my own version
|
|
||||||
```cpp
|
```cpp
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
|
@ -99,27 +98,34 @@ public:
|
||||||
```
|
```
|
||||||
|
|
||||||
Recursion:
|
Recursion:
|
||||||
==TODO== Needs revision!
|
|
||||||
```cpp
|
```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 {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
ListNode *reverseList(ListNode *head) {
|
ListNode *reverseList(ListNode *head) {
|
||||||
// Base case: reached the end of list
|
// Recursion
|
||||||
if (!head || !(head->next)) {
|
if (head == nullptr || head->next == nullptr) {
|
||||||
|
// base case: return the tail
|
||||||
return head;
|
return head;
|
||||||
}
|
}
|
||||||
|
|
||||||
// node is the end of the initial linked list, which stays the same
|
// have to call itself before modifying, since head->next will point to
|
||||||
ListNode *node = reverseList(head->next);
|
// nullptr
|
||||||
|
ListNode *newHead = reverseList(head->next);
|
||||||
|
|
||||||
// move head after head->next
|
|
||||||
// notice that the node before head still points to head!
|
|
||||||
head->next->next = head;
|
head->next->next = head;
|
||||||
|
head->next = nullptr;
|
||||||
|
|
||||||
// since the order is reversed, head->next now points to the tail of the linked list. This is the genius part of this algorithm
|
return newHead;
|
||||||
head->next = NULL;
|
|
||||||
|
|
||||||
return node;
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
```
|
```
|
Loading…
Reference in a new issue