{"id":27556,"date":"2018-02-06T20:56:54","date_gmt":"2018-02-06T15:26:54","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27556"},"modified":"2018-02-06T20:56:54","modified_gmt":"2018-02-06T15:26:54","slug":"c-programming-merge-two-sorted-linked-lists-such-that-merged-list-is-in-reverse-order-2","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/c-programming-merge-two-sorted-linked-lists-such-that-merged-list-is-in-reverse-order-2\/","title":{"rendered":"C Programming-Merge two sorted linked lists such that merged list is in reverse order"},"content":{"rendered":"<p>Given two linked lists sorted in increasing order. Merge them such a way that the result list is in decreasing order (reverse order).<\/p>\n<p><strong>Examples:<\/strong><\/p>\n<pre>Input:  a: 5-&gt;10-&gt;15-&gt;40\r\n        b: 2-&gt;3-&gt;20 \r\nOutput: res: 40-&gt;20-&gt;15-&gt;10-&gt;5-&gt;3-&gt;2\r\n\r\nInput:  a: NULL\r\n        b: 2-&gt;3-&gt;20 \r\nOutput: res: 20-&gt;3-&gt;2<\/pre>\n<p>A <strong>Simple Solution<\/strong> is to do following.<br \/>\n1) Reverse first list \u2018a\u2019.<br \/>\n2) Reverse second list \u2018b\u2019.<br \/>\n3) Merge two reversed lists.<\/p>\n<p>Another Simple Solution is first Merge both lists, then reverse the merged list.<\/p>\n<p>Both of the above solutions require two traversals of linked list.<\/p>\n<p><strong>How to solve without reverse, O(1) auxiliary space (in-place) and only one traversal of both lists?<\/strong><br \/>\nThe idea is to follow merge style process. Initialize result list as empty. Traverse both lists from beginning to end. Compare current nodes of both lists and insert smaller of two at the beginning of the result list.<\/p>\n<pre>1) Initialize result list as empty: res = NULL.\r\n2) Let 'a' and 'b' be heads first and second lists respectively.\r\n3) While (a != NULL and b != NULL)\r\n    a) Find the smaller of two (Current 'a' and 'b')\r\n    b) Insert the smaller value node at the front of result.\r\n    c) Move ahead in the list of smaller node. \r\n4) If 'b' becomes NULL before 'a', insert all nodes of 'a' \r\n   into result list at the beginning.\r\n5) If 'a' becomes NULL before 'b', insert all nodes of 'a' \r\n   into result list at the beginning.<\/pre>\n<p><strong>C Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-c code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-c code-embed-code\">\/* Given two sorted non-empty linked lists. Merge them in<br\/>   such a way that the result list will be in reverse<br\/>   order. Reversing of linked list is not allowed. Also,<br\/>   extra space should be O(1) *\/<br\/>#include&lt;iostream&gt;<br\/>using namespace std;<br\/> <br\/>\/* Link list Node *\/<br\/>struct Node<br\/>{<br\/>    int key;<br\/>    struct Node* next;<br\/>};<br\/> <br\/>\/\/ Given two non-empty linked lists &#039;a&#039; and &#039;b&#039;<br\/>Node* SortedMerge(Node *a, Node *b)<br\/>{<br\/>    \/\/ If both lists are empty<br\/>    if (a==NULL &amp;&amp; b==NULL) return NULL;<br\/> <br\/>    \/\/ Initialize head of resultant list<br\/>    Node *res = NULL;<br\/> <br\/>    \/\/ Traverse both lists while both of then<br\/>    \/\/ have nodes.<br\/>    while (a != NULL &amp;&amp; b != NULL)<br\/>    {<br\/>        \/\/ If a&#039;s current value is smaller or equal to<br\/>        \/\/ b&#039;s current value.<br\/>        if (a-&gt;key &lt;= b-&gt;key)<br\/>        {<br\/>            \/\/ Store next of current Node in first list<br\/>            Node *temp = a-&gt;next;<br\/> <br\/>            \/\/ Add &#039;a&#039; at the front of resultant list<br\/>            a-&gt;next = res;<br\/>            res = a;<br\/> <br\/>            \/\/ Move ahead in first list<br\/>            a = temp;<br\/>        }<br\/> <br\/>        \/\/ If a&#039;s value is greater. Below steps are similar<br\/>        \/\/ to above (Only &#039;a&#039; is replaced with &#039;b&#039;)<br\/>        else<br\/>        {<br\/>            Node *temp = b-&gt;next;<br\/>            b-&gt;next = res;<br\/>            res = b;<br\/>            b = temp;<br\/>        }<br\/>    }<br\/> <br\/>    \/\/ If second list reached end, but first list has<br\/>    \/\/ nodes. Add remaining nodes of first list at the<br\/>    \/\/ front of result list<br\/>    while (a != NULL)<br\/>    {<br\/>        Node *temp = a-&gt;next;<br\/>        a-&gt;next = res;<br\/>        res = a;<br\/>        a = temp;<br\/>    }<br\/> <br\/>    \/\/ If first list reached end, but second list has<br\/>    \/\/ node. Add remaining nodes of first list at the<br\/>    \/\/ front of result list<br\/>    while (b != NULL)<br\/>    {<br\/>        Node *temp = b-&gt;next;<br\/>        b-&gt;next = res;<br\/>        res = b;<br\/>        b = temp;<br\/>    }<br\/> <br\/>    return res;<br\/>}<br\/> <br\/>\/* Function to print Nodes in a given linked list *\/<br\/>void printList(struct Node *Node)<br\/>{<br\/>    while (Node!=NULL)<br\/>    {<br\/>        cout &lt;&lt; Node-&gt;key &lt;&lt; &quot; &quot;;<br\/>        Node = Node-&gt;next;<br\/>    }<br\/>}<br\/> <br\/>\/* Utility function to create a new node with<br\/>   given key *\/<br\/>Node *newNode(int key)<br\/>{<br\/>    Node *temp = new Node;<br\/>    temp-&gt;key = key;<br\/>    temp-&gt;next = NULL;<br\/>    return temp;<br\/>}<br\/> <br\/>\/* Drier program to test above functions*\/<br\/>int main()<br\/>{<br\/>    \/* Start with the empty list *\/<br\/>    struct Node* res = NULL;<br\/> <br\/>    \/* Let us create two sorted linked lists to test<br\/>       the above functions. Created lists shall be<br\/>         a: 5-&gt;10-&gt;15<br\/>         b: 2-&gt;3-&gt;20  *\/<br\/>    Node *a = newNode(5);<br\/>    a-&gt;next = newNode(10);<br\/>    a-&gt;next-&gt;next = newNode(15);<br\/> <br\/>    Node *b = newNode(2);<br\/>    b-&gt;next = newNode(3);<br\/>    b-&gt;next-&gt;next = newNode(20);<br\/> <br\/>    cout &lt;&lt; &quot;List A before merge: \\n&quot;;<br\/>    printList(a);<br\/> <br\/>    cout &lt;&lt; &quot;\\nList B before merge: \\n&quot;;<br\/>    printList(b);<br\/> <br\/>    \/* merge 2 increasing order LLs in descresing order *\/<br\/>    res = SortedMerge(a, b);<br\/> <br\/>    cout &lt;&lt; &quot;\\nMerged Linked List is: \\n&quot;;<br\/>    printList(res);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output:<\/strong><\/p>\n<pre>List A before merge: \r\n5 10 15 \r\nList B before merge: \r\n2 3 20 \r\nMerged Linked List is: \r\n20 15 10 5 3 2<\/pre>\n<p>This solution traverses both lists only once, doesn\u2019t require reverse and works in-place.<\/p>\n<p>&nbsp;<\/p>\n","protected":false},"excerpt":{"rendered":"<p>C Programming-Merge two sorted linked lists such that merged list is in reverse order-Linked list<br \/>\nGiven two linked lists sorted <\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79476,79478],"tags":[81476,81750,81477,81749,81748,81474,81479,81483,81475],"class_list":["post-27556","post","type-post","status-publish","format-standard","hentry","category-linked-list","category-singly-linked-list","tag-merge-sort-linked-list-c","tag-merge-two-linked-list-in-c","tag-merge-two-sorted-array","tag-merge-two-sorted-linked-lists-hackerrank","tag-merge-two-sorted-linked-lists-in-java","tag-merge-two-sorted-linked-lists-python","tag-merge-two-sorted-lists-python","tag-merge-two-unsorted-linked-lists-in-c","tag-merging-of-linked-list-in-data-structure"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27556","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/comments?post=27556"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27556\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27556"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27556"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27556"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}