diff --git a/CS notes/pages/Leetcode Reverse-Linked-List.md b/CS notes/pages/Leetcode Reverse-Linked-List.md index e89e056..e6fc48c 100644 --- a/CS notes/pages/Leetcode Reverse-Linked-List.md +++ b/CS notes/pages/Leetcode Reverse-Linked-List.md @@ -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; + } +}; ``` \ No newline at end of file