vault backup: 2022-07-02 08:27:19

This commit is contained in:
juan 2022-07-02 08:27:19 +08:00
parent 726dc67f4a
commit ee1e87b6af

View file

@ -75,8 +75,7 @@ The in place insert is easier to understand, and simple to implement, using a ve
### Solution
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.
==TODO==: Make my own version
Insertion, iteration
```cpp
class Solution {
public:
@ -99,27 +98,34 @@ public:
```
Recursion:
==TODO== Needs revision!
```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) {
// Base case: reached the end of list
if (!head || !(head->next)) {
// Recursion
if (head == nullptr || head->next == nullptr) {
// base case: return the tail
return head;
}
// node is the end of the initial linked list, which stays the same
ListNode *node = reverseList(head->next);
// have to call itself before modifying, since head->next will point to
// 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 = 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
head->next = NULL;
return node;
return newHead;
}
};
```