vault backup: 2022-06-15 23:14:20
This commit is contained in:
parent
3dc4af3c98
commit
8f4d1e1091
|
@ -8,7 +8,7 @@
|
|||
##### Data structures:
|
||||
#DS #linked_list
|
||||
##### Difficulty:
|
||||
#leetcode #coding_problem #difficulty-easy
|
||||
#leetcode #coding_problem #difficulty-medium
|
||||
##### Lists:
|
||||
#CS_list_need_understanding #CS_list_need_practicing
|
||||
##### Related topics:
|
||||
|
@ -62,6 +62,8 @@ 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
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
|
@ -70,14 +72,35 @@ public:
|
|||
// pre is before head, and insert any element after pre.
|
||||
pre->next = head;
|
||||
while (cur && cur->next) {
|
||||
// Move cur->next after pre.
|
||||
// temp points to head
|
||||
ListNode *temp = pre->next;
|
||||
// Move cur->next after pre.
|
||||
pre->next = cur->next;
|
||||
// Fix pointers, because cur->next is unchanged when changing position.
|
||||
cur->next = cur->next->next;
|
||||
|
||||
pre->next->next = temp;
|
||||
}
|
||||
return pre->next;
|
||||
}
|
||||
};
|
||||
```
|
||||
|
||||
Recursion:
|
||||
```cpp
|
||||
class Solution {
|
||||
public:
|
||||
ListNode *reverseList(ListNode *head) {
|
||||
// Base case: reached the end of list
|
||||
if (!head || !(head->next)) {
|
||||
return head;
|
||||
}
|
||||
|
||||
// node is the end of linked list, which stays the same and untouched
|
||||
ListNode *node = reverseList(head->next);
|
||||
// change head->next
|
||||
head->next->next = head;
|
||||
head->next = NULL;
|
||||
return node;
|
||||
}
|
||||
};
|
||||
```
|
Loading…
Reference in a new issue