{"id":1113,"date":"2023-12-18T13:00:00","date_gmt":"2023-12-18T13:00:00","guid":{"rendered":"https:\/\/favtutor.com\/articles\/?p=1113"},"modified":"2023-12-22T07:18:23","modified_gmt":"2023-12-22T07:18:23","slug":"merge-two-sorted-lists","status":"publish","type":"post","link":"https:\/\/favtutor.com\/articles\/merge-two-sorted-lists\/","title":{"rendered":"Merge Two Sorted Linked Lists (C++, Java, Python)"},"content":{"rendered":"\n<p>Linked lists are fundamental data structures in programming, providing an efficient way to organize and manipulate data. When dealing with two sorted linked lists, a common operation is joining them into a single one. In this article, we&#8217;ll learn how to merge two sorted linked lists using the recursive approach.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>What is the Merge Two Sorted Lists Problem?<\/strong><\/h2>\n\n\n\n<p>Just to recap, A <a href=\"https:\/\/favtutor.com\/blog-details\/linked-list-data-structure\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/blog-details\/linked-list-data-structure\">linked list<\/a> is a linear data structure in which elements are stored in nodes. Each node points to the next node in the sequence. When we say the list is sorted, it means that the elements are arranged in ascending or descending order.<\/p>\n\n\n\n<p>Merging two sorted linked lists preserves this order, which makes it easier for search algorithms to perform efficiently. We usually find the data in two different lists and it becomes necessary to join them to work on it. Sometimes, we need to present the output in a combined way.<\/p>\n\n\n\n<p>Here is the problem statement: <strong>We are given 2 sorted linked lists, sorted in ascending order and we have to merge them in a way that maintains the sorted order.<\/strong><\/p>\n\n\n\n<p>Let\u2019s look at an example,<\/p>\n\n\n\n<p>LinkedList 1 =&nbsp; 1\u2192 3\u2192 6<\/p>\n\n\n\n<p>LinkedList 2 =&nbsp; 2\u2192 4\u2192 5<\/p>\n\n\n\n<p>Resultant List = 1\u2192 2\u2192 3\u2192 4\u2192 5\u2192 6<\/p>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/xd3S0qzZULZP3ZbBFyegJDI-6TEsZN0bL8ozd0rP_DFZISfbV3ztmSDxaffFb_ux4vRwgo4YRStuaJgyyPny4Wvkz1DEkwzA4SybF1Svv7HOMN_zNVPOSoI55hiNz-bPEP-MEhf4O2SDMeY9M3sLYqc\" alt=\"Example of Merging two sorted linked lists\"\/><\/figure>\n<\/div>\n\n\n<p>We can see the resultant list is sorted and contains the elements of both lists.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Brute Force Approach<\/strong><\/h2>\n\n\n\n<p>The simplest way to solve it is by using the brute-force approach. We can create a dummy node with a value of 0 to simplify this node and merge our present lists to this in sorted order. We will iterate both lists and keep adding the elements to this node.<\/p>\n\n\n\n<p>Here are the steps involved in this straightforward technique:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>First of all, we will create a dummy node with a value of 0&nbsp;<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/FgGH6Z0qh05AshI6Hs2ULK0fztymkS4cdMFFBLMW5T0nuDQbhfo__PV71QqBO-VHdAJXyvbzeASDSYSgiFTK68wVwMffuks32aYJUBfZUQl_oYokm1ZBDuMQKx585ql39ti4ZClaLVqDa7oEwau1nW0\" alt=\"create a dummy node\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Now we will create a pointer current initially pointing to the dummy node.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/IDL7cZSUjkk_AA5q649p-hfmd02vIfpaM6aT5z7VI6fYnWuo2hMynrwIj2gw-1SY3UUW45kSIncoUKaewltQY_iLF7VaTBKZtb8A1CwtgMZ4XWhZ5GWW7CmIKPE-6bCJZQBsx0ugKCgiWvbu2fn7Mzs\" alt=\"create a pointer current\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Iterate until both input lists (l1 and l2) are exhausted. Compare the values of the current nodes in l1 and l2.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/h4Ncoe3faOYHybUywU7GFWrYfkirL9TDxrBvV2A2bi0AWUtjQuZra3_9Ws_nFRUyalIbeqQCyby6MUk4jtgNIP632kMB_n_xoIwU03kIGqFWJRCAE_iCOsRY-ysc2gc806Gc0G649lxqRPnbqUaRxK0\" alt=\"Compare the values of the current nodes\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>Create a new node with the smaller value and append it to the merged list.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/Y4YAwVUa_toJJawU1X9myHpuV2-O5D6J3fCavrljR5WcuvhlOD1vHEWa_bXx_NV7UOk5h86we1HoDhBHiV65iR_pgjDXv7WvFipezpPK02e5syD7u7sW1tzzfb7quIwqf_CBW-Lep8rEaTYJ09ErH98\" alt=\"append it to the merged list\"\/><\/figure>\n<\/div>\n\n\n<ul class=\"wp-block-list\">\n<li>After the loop, if either l1 or l2 is not exhausted, append the remaining nodes to the merged list.<\/li>\n\n\n\n<li>Return dummy-&gt;next after all iterations.<\/li>\n<\/ul>\n\n\n<div class=\"wp-block-image\">\n<figure class=\"aligncenter\"><img decoding=\"async\" src=\"https:\/\/lh7-us.googleusercontent.com\/0ZXgb9xDcDYhThGPpTtgD7_7orJgDngXO1lKA88KxFo1JXRynf-dujqQRtMsZvPVrB8tC7bujK28oqNW7r4D9j3taqrFYt6jXc3rG8LLsKxs_0-GxfyHo3-z29zEyW_5SCz9ay_caTys90O2iSJirFw\" alt=\"Return next node of dummy\"\/><\/figure>\n<\/div>\n\n\n<p>The Time Complexity of this approach is O(max(m, n)), where m and n are the sizes of both the lists.\u00a0 The Space Complexity of this approach is O(max(m, n)).<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Recursive Approach to Merge Two-Sorted Lists<\/strong><\/h2>\n\n\n\n<p><strong>In the recursive approach, we will use a recursion to merge two sorted linked lists.<\/strong> We first select the smaller of the current nodes from both lists and then recursively merge the remaining lists.<\/p>\n\n\n\n<p>We will follow the same steps as we were following in the brute force approach. But we will use <a href=\"https:\/\/favtutor.com\/blogs\/java-recursion\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/blogs\/java-recursion\">recursion<\/a> to do it easily. Following are the steps involved in merging two sorted linked lists using a recursive approach:<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li>Firstly we will declare the base case for our recursive function that If either l1 or l2 is empty, return the other list<\/li>\n\n\n\n<li>Now, Compare the values of the current nodes in l1 and l2 and choose the smaller value as the current node for the merged list.<\/li>\n\n\n\n<li>If l1 has the smaller value, recursively call the recursive function with parameters l1-&gt;next and l2.<\/li>\n\n\n\n<li>If l2 has the smaller value, recursively call the recursive function with parameters l1 and l2-&gt;next.<\/li>\n\n\n\n<li>Return the current node (either l1 or l2) as the merged list.<\/li>\n<\/ol>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>C++ Code<\/strong><\/h3>\n\n\n\n<p>Here is the C++ program to merge two sorted lists using recursion:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-c++src&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;C++&quot;,&quot;modeName&quot;:&quot;cpp&quot;}\">#include &lt;bits\/stdc++.h&gt;\nusing namespace std;\n\n\/\/ Definition for singly-linked list.\nstruct ListNode {\n    int val;\n    ListNode* next;\n    ListNode(int x) : val(x), next(nullptr) {}\n};\n\nListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {\n    \/\/ Base cases: if either list is empty, return the other list\n    if (!l1) return l2;\n    if (!l2) return l1;\n\n    \/\/ Choose the smaller value as the current node\n    if (l1-&gt;val &lt; l2-&gt;val) {\n        \/\/ Recursively merge the rest of the lists starting from l1-&gt;next and l2\n        l1-&gt;next = mergeTwoLists(l1-&gt;next, l2);\n        return l1;\n    } else {\n        \/\/ Recursively merge the rest of the lists starting from l1 and l2-&gt;next\n        l2-&gt;next = mergeTwoLists(l1, l2-&gt;next);\n        return l2;\n    }\n}\n\nint main() {\n    \/\/ Example usage\n    \/\/ Create sorted linked lists\n    ListNode* list1 = new ListNode(1);\n    list1-&gt;next = new ListNode(3);\n    list1-&gt;next-&gt;next = new ListNode(6);\n\n    ListNode* list2 = new ListNode(2);\n    list2-&gt;next = new ListNode(4);\n    list2-&gt;next-&gt;next = new ListNode(5);\n\n    \/\/ Merge the lists\n    ListNode* mergedList = mergeTwoLists(list1, list2);\n\n    \/\/ Print the merged list\n    while (mergedList) {\n        cout &lt;&lt; mergedList-&gt;val &lt;&lt; &quot; &quot;;\n        mergedList = mergedList-&gt;next;\n    }\n\n    return 0;\n}<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Python Code<\/strong><\/h3>\n\n\n\n<p>Here is the Python program to merge two sorted linked lists:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;python&quot;,&quot;mime&quot;:&quot;text\/x-python&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Python&quot;,&quot;modeName&quot;:&quot;python&quot;}\">class ListNode:\n    def __init__(self, val=0, next=None):\n        self.val = val\n        self.next = next\n\ndef mergeTwoLists(l1, l2):\n    # Create a dummy node to serve as the head of the merged list\n    dummy = ListNode()\n    current = dummy\n\n    # Loop until one of the lists is empty\n    while l1 and l2:\n        if l1.val &lt; l2.val:\n            # Attach the current node to the smaller node from l1\n            current.next = l1\n            l1 = l1.next\n        else:\n            # Attach the current node to the smaller node from l2\n            current.next = l2\n            l2 = l2.next\n\n        # Move the current pointer to the last node\n        current = current.next\n\n    # Attach the remaining nodes from the non-empty list (if any)\n    if l1:\n        current.next = l1\n    elif l2:\n        current.next = l2\n\n    # Return the merged list starting from the dummy node's next\n    return dummy.next\n\n# Example usage\nlist1 = ListNode(1, ListNode(3, ListNode(6)))\nlist2 = ListNode(2, ListNode(4, ListNode(5)))\n\nmergedList = mergeTwoLists(list1, list2)\n\n# Print the merged list\nwhile mergedList:\n    print(mergedList.val, end=&quot; &quot;)\n    mergedList = mergedList.next<\/pre><\/div>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>Java Code<\/strong><\/h3>\n\n\n\n<p>You can implement it in Java as well:<\/p>\n\n\n\n<div class=\"wp-block-codemirror-blocks-code-block code-block\"><pre class=\"CodeMirror\" data-setting=\"{&quot;mode&quot;:&quot;clike&quot;,&quot;mime&quot;:&quot;text\/x-java&quot;,&quot;theme&quot;:&quot;material&quot;,&quot;lineNumbers&quot;:true,&quot;styleActiveLine&quot;:false,&quot;lineWrapping&quot;:false,&quot;readOnly&quot;:true,&quot;language&quot;:&quot;Java&quot;,&quot;modeName&quot;:&quot;java&quot;}\">public class MergeSortedLinkedLists {\n    static class ListNode {\n    int val;\n    ListNode next;\n\n    ListNode(int x) {\n        val = x;\n        next = null;\n    }\n}\n\n    public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {\n        \/\/ Create a dummy node to simplify the code\n        ListNode dummy = new ListNode(0);\n        ListNode current = dummy;\n\n        \/\/ Iterate while both lists are not empty\n        while (l1 != null &amp;&amp; l2 != null) {\n            if (l1.val &lt; l2.val) {\n                current.next = l1;\n                l1 = l1.next;\n            } else {\n                current.next = l2;\n                l2 = l2.next;\n            }\n            current = current.next;\n        }\n\n        \/\/ If one list is not empty, append the remaining nodes\n        if (l1 != null) {\n            current.next = l1;\n        } else {\n            current.next = l2;\n        }\n\n        \/\/ Return the merged list starting from the next of the dummy node\n        return dummy.next;\n    }\n\n    \/\/ Helper method to print the merged list\n    public static void printList(ListNode head) {\n        while (head != null) {\n            System.out.print(head.val + &quot; &quot;);\n            head = head.next;\n        }\n        System.out.println();\n    }\n\n    public static void main(String[] args) {\n        \/\/ Example usage\n        ListNode list1 = new ListNode(1);\n        list1.next = new ListNode(3);\n        list1.next.next = new ListNode(6);\n\n        ListNode list2 = new ListNode(2);\n        list2.next = new ListNode(4);\n        list2.next.next = new ListNode(5);\n\n        \/\/ Merge the lists\n        ListNode mergedList = mergeTwoLists(list1, list2);\n\n        \/\/ Print the merged list\n        System.out.println(&quot;Merged List:&quot;);\n        printList(mergedList);\n    }\n}<\/pre><\/div>\n\n\n\n<p><strong>Output:<\/strong><\/p>\n\n\n\n<pre class=\"wp-block-code has-black-color has-text-color has-background\" style=\"background-color:#fedcba\"><code>1 2 3 4 5 6&nbsp;<\/code><\/pre>\n\n\n\n<p>The time complexity of merging two sorted lists using recursion is O(n), where n is the total number of nodes in both linked lists. This is because the function processes each node exactly once, and the number of recursive calls is proportional to the total number of nodes in the input lists.<\/p>\n\n\n\n<p>The Space Complexity is O(n) (due to the function call stack during recursion), O(1) auxiliary space.<\/p>\n\n\n\n<p>In the end, here you can compare both approaches and see that recursive is the best one:<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table><tbody><tr><td><strong>Approach<\/strong><\/td><td><strong>Time complexity<\/strong><\/td><td><strong>Space complexity<\/strong><\/td><td><strong>Details<\/strong><\/td><\/tr><tr><td>Brute force <\/td><td>O(max(m, n))<\/td><td>O(max(m, n))<\/td><td>Create a dummy node with a value of 0 to simplify this node and merge our present lists to this in sorted order.<\/td><\/tr><tr><td>Recursive <\/td><td>O(n)<\/td><td>O(1)<\/td><td>Using recursion to save time and space.<\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p>Another interesting problem related to <a href=\"https:\/\/favtutor.com\/articles\/detect-linked-list-cycle\/\" data-type=\"link\" data-id=\"https:\/\/favtutor.com\/articles\/detect-linked-list-cycle\/\">linked lists is to detect a cycle<\/a>.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\"><strong>Conclusion&nbsp;<\/strong><\/h2>\n\n\n\n<p>While this problem looks easy at first glance, it is very difficult to find the solution instantly in a solution. That&#8217;s why it is also included in <a href=\"https:\/\/leetcode.com\/problems\/merge-two-sorted-lists\/\" data-type=\"link\" data-id=\"https:\/\/leetcode.com\/problems\/merge-two-sorted-lists\/\" target=\"_blank\" rel=\"noreferrer noopener nofollow\">leetcode<\/a> and other interview question websites as well. But now you know how to merge two sorted linked lists using the recursion, along with its time and space complexities.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to merge two sorted linked lists in this leetcode problem using recursion, with implementation in C++, Java and Python.<\/p>\n","protected":false},"author":12,"featured_media":1115,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":{"jnews-multi-image_gallery":[],"jnews_single_post":null,"jnews_primary_category":{"id":"","hide":""},"footnotes":""},"categories":[7],"tags":[14,15],"class_list":["post-1113","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-data-structures-algorithms","tag-dsa","tag-leetcode"],"_links":{"self":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1113","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/users\/12"}],"replies":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/comments?post=1113"}],"version-history":[{"count":4,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1113\/revisions"}],"predecessor-version":[{"id":1144,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/posts\/1113\/revisions\/1144"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media\/1115"}],"wp:attachment":[{"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/media?parent=1113"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/categories?post=1113"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/favtutor.com\/articles\/wp-json\/wp\/v2\/tags?post=1113"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}