diff --git a/OJ notes/pages/Leetcode 01-Matrix.md b/OJ notes/pages/Leetcode 01-Matrix.md index f689e44..036aad9 100644 --- a/OJ notes/pages/Leetcode 01-Matrix.md +++ b/OJ notes/pages/Leetcode 01-Matrix.md @@ -1,4 +1,4 @@ -sh# Leetcode 01-Matrix +# Leetcode 01-Matrix #### 2022-07-17 03:15 diff --git a/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md b/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md index 290b0a4..d68343e 100644 --- a/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md +++ b/OJ notes/pages/Leetcode Merge-Two-Sorted-Lists.md @@ -4,7 +4,7 @@ --- ##### Algorithms: -#algorithm #two_pointers +#algorithm #two_pointers #recursion ##### Data structures: #DS #linked_list ##### Difficulty: @@ -61,9 +61,51 @@ Return _the head of the merged linked list_. ### Thoughts +#### Two pointers method + This is a #two_pointers algorithm, I've done similar problems at leetcode's array list. The only thing to watch out for is when there is one list remaining, remember to add the tails. + +#### Recursion + +Very simple for recursion + +##### Base Case: +- Both are nullptr -> return nullptr +- One is nullptr -> return another + +##### Pseudocode: +- Check for base case: +- if list1->val > list2->val, list2's next should be the merged result +- if list2->val > list1->val, list1's next should be the merged result. + ### Solution +Recursion +```cpp +class Solution { +public: + ListNode *mergeTwoLists(ListNode *list1, ListNode *list2) { + // Recursion + // Base case, one is empty or both empty + if (!list1) { + return list2; + } else if (!list2) { + return list1; + } + + if (list1->val > list2->val) { + // insert list1 after list2 + list2->next = mergeTwoLists(list1, list2->next); + return list2; + } else { + list1->next = mergeTwoLists(list1->next, list2); + return list1; + } + } +}; +``` + +Two pointers ```cpp /** * Definition for singly-linked list.