# Leetcode Merge-Two-Sorted-Lists #### 2022-06-14 22:57 --- ##### Algorithms: #algorithm #two_pointers #recursion ##### Data structures: #DS #linked_list ##### Difficulty: #leetcode #coding_problem #difficulty-easy ##### Related topics: ##### Links: - [Link to problem](https://leetcode.com/problems/merge-two-sorted-lists/) --- ### Problem You are given the heads of two sorted linked lists `list1` and `list2`. Merge the two lists in a one **sorted** list. The list should be made by splicing together the nodes of the first two lists. Return _the head of the merged linked list_. #### Examples **Example 1:** ![](https://assets.leetcode.com/uploads/2020/10/03/merge_ex1.jpg) ```markdown **Input:** list1 = [1,2,4], list2 = [1,3,4] **Output:** [1,1,2,3,4,4] ``` **Example 2:** ```markdown **Input:** list1 = [], list2 = [] **Output:** [] ``` **Example 3:** ```markdown **Input:** list1 = [], list2 = [0] **Output:** [0] ``` #### Constraints - The number of nodes in both lists is in the range `[0, 50]`. - `-100 <= Node.val <= 100` - Both `list1` and `list2` are sorted in **non-decreasing** order. ### 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. * 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 *mergeTwoLists(ListNode *list1, ListNode *list2) { // 2 Pointers, Space and time O(m + n); ListNode *ptr1 = list1; ListNode *ptr2 = list2; ListNode *dummyHead = new ListNode(); ListNode *ptr3 = dummyHead; while (ptr2 != NULL && ptr1 != NULL) { if (ptr2->val <= ptr1->val) { ptr3->next = ptr2; ptr2 = ptr2->next; } else { ptr3->next = ptr1; ptr1 = ptr1->next; } ptr3 = ptr3->next; } if (ptr2 == NULL) { ptr3->next = ptr1; } else if (ptr1 == NULL) { ptr3->next = ptr2; } return dummyHead->next; } }; ```