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