{"id":27578,"date":"2018-04-04T19:30:25","date_gmt":"2018-04-04T14:00:25","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27578"},"modified":"2018-04-04T19:30:25","modified_gmt":"2018-04-04T14:00:25","slug":"java-programming-merge-two-sorted-linked-lists-merged-list-reverse-order","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/java-programming-merge-two-sorted-linked-lists-merged-list-reverse-order\/","title":{"rendered":"Java  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>Cpp \u00a0Programming:<\/strong><\/p>\n<div class=\"code-embed-wrapper\"> <div class=\"code-embed-infos\"> <\/div> <pre class=\"language-java code-embed-pre line-numbers\"  data-start=\"1\" data-line-offset=\"0\"><code class=\"language-java code-embed-code\">\/\/ Java program to merge two sorted linked list such that merged <br\/>\/\/ list is in reverse order<br\/> <br\/>\/\/ Linked List Class<br\/>class LinkedList {<br\/> <br\/>    Node head;  \/\/ head of list<br\/>    static Node a, b;<br\/> <br\/>    \/* Node Class *\/<br\/>    static class Node {<br\/> <br\/>        int data;<br\/>        Node next;<br\/> <br\/>        \/\/ Constructor to create a new node<br\/>        Node(int d) {<br\/>            data = d;<br\/>            next = null;<br\/>        }<br\/>    }<br\/> <br\/>    void printlist(Node node) {<br\/>        while (node != null) {<br\/>            System.out.print(node.data + &quot; &quot;);<br\/>            node = node.next;<br\/>        }<br\/>    }<br\/> <br\/>    Node sortedmerge(Node node1, Node node2) {<br\/>         <br\/>        \/\/ if both the nodes are null<br\/>        if (node1 == null &amp;&amp; node2 == null) {<br\/>            return null;<br\/>        }<br\/> <br\/>        \/\/ resultant node<br\/>        Node res = null;<br\/> <br\/>        \/\/ if both of them have nodes present traverse them<br\/>        while (node1 != null &amp;&amp; node2 != null) {<br\/> <br\/>            \/\/ Now compare both nodes current data<br\/>            if (node1.data &lt;= node2.data) {<br\/>                Node temp = node1.next;<br\/>                node1.next = res;<br\/>                res = node1;<br\/>                node1 = temp;<br\/>            } else {<br\/>                Node temp = node2.next;<br\/>                node2.next = res;<br\/>                res = node2;<br\/>                node2 = 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 (node1 != null) {<br\/>            Node temp = node1.next;<br\/>            node1.next = res;<br\/>            res = node1;<br\/>            node1 = 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 (node2 != null) {<br\/>            Node temp = node2.next;<br\/>            node2.next = res;<br\/>            res = node2;<br\/>            node2 = temp;<br\/>        }<br\/> <br\/>        return res;<br\/> <br\/>    }<br\/> <br\/>    public static void main(String[] args) {<br\/> <br\/>        LinkedList list = new LinkedList();<br\/>        Node result = 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\/>        list.a = new Node(5);<br\/>        list.a.next = new Node(10);<br\/>        list.a.next.next = new Node(15);<br\/> <br\/>        list.b = new Node(2);<br\/>        list.b.next = new Node(3);<br\/>        list.b.next.next = new Node(20);<br\/> <br\/>        System.out.println(&quot;List a before merge :&quot;);<br\/>        list.printlist(a);<br\/>        System.out.println(&quot;&quot;);<br\/>        System.out.println(&quot;List b before merge :&quot;);<br\/>        list.printlist(b);<br\/> <br\/>        \/\/ merge two sorted linkedlist in decreasing order<br\/>        result = list.sortedmerge(a, b);<br\/>        System.out.println(&quot;&quot;);<br\/>        System.out.println(&quot;Merged linked list : &quot;);<br\/>        list.printlist(result);<br\/> <br\/>    }<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>Java  Programming-Merge two sorted linked lists such that merged list is in reverse order-Linked list<br \/>\nGiven two linked lists sorted in increasing<\/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-27578","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\/27578","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=27578"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27578\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27578"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27578"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27578"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}