vault backup: 2022-06-15 23:14:20
This commit is contained in:
parent
3dc4af3c98
commit
8f4d1e1091
|
@ -8,7 +8,7 @@
|
||||||
##### Data structures:
|
##### Data structures:
|
||||||
#DS #linked_list
|
#DS #linked_list
|
||||||
##### Difficulty:
|
##### Difficulty:
|
||||||
#leetcode #coding_problem #difficulty-easy
|
#leetcode #coding_problem #difficulty-medium
|
||||||
##### Lists:
|
##### Lists:
|
||||||
#CS_list_need_understanding #CS_list_need_practicing
|
#CS_list_need_understanding #CS_list_need_practicing
|
||||||
##### Related topics:
|
##### Related topics:
|
||||||
|
@ -62,6 +62,8 @@ 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.
|
||||||
|
==TODO==: Make my own version
|
||||||
```cpp
|
```cpp
|
||||||
class Solution {
|
class Solution {
|
||||||
public:
|
public:
|
||||||
|
@ -70,14 +72,35 @@ public:
|
||||||
// pre is before head, and insert any element after pre.
|
// pre is before head, and insert any element after pre.
|
||||||
pre->next = head;
|
pre->next = head;
|
||||||
while (cur && cur->next) {
|
while (cur && cur->next) {
|
||||||
// Move cur->next after pre.
|
// temp points to head
|
||||||
ListNode *temp = pre->next;
|
ListNode *temp = pre->next;
|
||||||
|
// Move cur->next after pre.
|
||||||
pre->next = cur->next;
|
pre->next = cur->next;
|
||||||
|
// Fix pointers, because cur->next is unchanged when changing position.
|
||||||
cur->next = cur->next->next;
|
cur->next = cur->next->next;
|
||||||
|
|
||||||
pre->next->next = temp;
|
pre->next->next = temp;
|
||||||
}
|
}
|
||||||
return pre->next;
|
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