diff --git a/OJ notes/pages/Leetcode Reverse-Linked-List.md b/OJ notes/pages/Leetcode Reverse-Linked-List.md index 7fb69cf..2a62888 100644 --- a/OJ notes/pages/Leetcode Reverse-Linked-List.md +++ b/OJ notes/pages/Leetcode Reverse-Linked-List.md @@ -122,17 +122,32 @@ public: Recursion: +2022-09-20 version +```cpp +class Solution { +public: + ListNode *reverseList(ListNode *head) { + // Recursion + + // Base case: no need to reverse: + if (head == nullptr || head->next == nullptr) { + return head; + } + + // assuming we have the head of reversed sub-list + // head->next still points to next one in the unchanged order, + // or the tail of the reversed list + auto newHead = reverseList(head->next); + + head->next->next = head; + head->next = nullptr; + + return newHead; + } +}; +``` + ```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) {