{"id":27368,"date":"2018-02-01T21:31:00","date_gmt":"2018-02-01T16:01:00","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27368"},"modified":"2018-02-01T21:31:00","modified_gmt":"2018-02-01T16:01:00","slug":"merge-two-sorted-linked-lists","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/merge-two-sorted-linked-lists\/","title":{"rendered":"C Algorithm &#8211; Merge two sorted linked lists"},"content":{"rendered":"<p>Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order, and merges the two together into one list which is in increasing order. SortedMerge() should return the new list.<span id=\"more-3622\"><\/span> The new list should be made by splicing<br \/>\ntogether the nodes of the first two lists.<\/p>\n<p>For example if the first linked list a is 5-&gt;10-&gt;15 and the other linked list b is 2-&gt;3-&gt;20, then SortedMerge() should return a pointer to the head node of the merged list 2-&gt;3-&gt;5-&gt;10-&gt;15-&gt;20.<\/p>\n<p>There are many cases to deal with: either \u2018a\u2019 or \u2018b\u2019 may be empty, during processing either \u2018a\u2019 or \u2018b\u2019 may run out first, and finally there\u2019s the problem of starting the result list empty, and building it up while going through \u2018a\u2019 and \u2018b\u2019.<\/p>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 1 (Using Dummy Nodes)<\/strong><br \/>\nThe strategy here uses a temporary dummy node as the start of the result list. The pointer Tail always points to the last node in the result list, so appending new nodes is easy.<br \/>\nThe dummy node gives tail something to point to initially when the result list is empty. This dummy node is efficient, since it is only temporary, and it is allocated in the stack. The loop proceeds, removing one node from either \u2018a\u2019 or \u2018b\u2019, and adding it to tail. When<br \/>\nwe are done, the result is in dummy.next.<\/p>\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\">\/* C\/C++ program to merge two sorted linked lists *\/<br\/>#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/>#include&lt;assert.h&gt;<br\/> <br\/>\/* Link list node *\/<br\/>struct node<br\/>{<br\/>    int data;<br\/>    struct node* next;<br\/>};<br\/> <br\/>\/* pull off the front node of the source and put it in dest *\/<br\/>void MoveNode(struct node** destRef, struct node** sourceRef);<br\/> <br\/>\/* Takes two lists sorted in increasing order, and splices<br\/>   their nodes together to make one big sorted list which<br\/>   is returned.  *\/<br\/>struct node* SortedMerge(struct node* a, struct node* b)<br\/>{<br\/>    \/* a dummy first node to hang the result on *\/<br\/>    struct node dummy;<br\/> <br\/>    \/* tail points to the last result node  *\/<br\/>    struct node* tail = &amp;dummy;<br\/> <br\/>    \/* so tail-&gt;next is the place to add new nodes<br\/>      to the result. *\/<br\/>    dummy.next = NULL;<br\/>    while (1)<br\/>    {<br\/>        if (a == NULL)<br\/>        {<br\/>            \/* if either list runs out, use the<br\/>               other list *\/<br\/>            tail-&gt;next = b;<br\/>            break;<br\/>        }<br\/>        else if (b == NULL)<br\/>        {<br\/>            tail-&gt;next = a;<br\/>            break;<br\/>        }<br\/>        if (a-&gt;data &lt;= b-&gt;data)<br\/>            MoveNode(&amp;(tail-&gt;next), &amp;a);<br\/>        else<br\/>            MoveNode(&amp;(tail-&gt;next), &amp;b);<br\/> <br\/>        tail = tail-&gt;next;<br\/>    }<br\/>    return(dummy.next);<br\/>}<br\/> <br\/>\/* UTILITY FUNCTIONS *\/<br\/>\/* MoveNode() function takes the node from the front of the<br\/>   source, and move it to the front of the dest.<br\/>   It is an error to call this with the source list empty.<br\/> <br\/>   Before calling MoveNode():<br\/>   source == {1, 2, 3}<br\/>   dest == {1, 2, 3}<br\/> <br\/>   Affter calling MoveNode():<br\/>   source == {2, 3}<br\/>   dest == {1, 1, 2, 3} *\/<br\/>void MoveNode(struct node** destRef, struct node** sourceRef)<br\/>{<br\/>    \/* the front source node  *\/<br\/>    struct node* newNode = *sourceRef;<br\/>    assert(newNode != NULL);<br\/> <br\/>    \/* Advance the source pointer *\/<br\/>    *sourceRef = newNode-&gt;next;<br\/> <br\/>    \/* Link the old dest off the new node *\/<br\/>    newNode-&gt;next = *destRef;<br\/> <br\/>    \/* Move dest to point to the new node *\/<br\/>    *destRef = newNode;<br\/>}<br\/> <br\/> <br\/>\/* Function to insert a node at the beginging of the<br\/>   linked list *\/<br\/>void push(struct node** head_ref, int new_data)<br\/>{<br\/>    \/* allocate node *\/<br\/>    struct node* new_node =<br\/>        (struct node*) malloc(sizeof(struct node));<br\/> <br\/>    \/* put in the data  *\/<br\/>    new_node-&gt;data  = new_data;<br\/> <br\/>    \/* link the old list off the new node *\/<br\/>    new_node-&gt;next = (*head_ref);<br\/> <br\/>    \/* move the head to point to the new node *\/<br\/>    (*head_ref)    = new_node;<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\/>        printf(&quot;%d &quot;, node-&gt;data);<br\/>        node = node-&gt;next;<br\/>    }<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\/>    struct node* a = NULL;<br\/>    struct node* b = NULL;<br\/> <br\/>    \/* Let us create two sorted linked lists to test<br\/>      the functions<br\/>       Created lists, a: 5-&gt;10-&gt;15,  b: 2-&gt;3-&gt;20 *\/<br\/>    push(&amp;a, 15);<br\/>    push(&amp;a, 10);<br\/>    push(&amp;a, 5);<br\/> <br\/>    push(&amp;b, 20);<br\/>    push(&amp;b, 3);<br\/>    push(&amp;b, 2);<br\/> <br\/>    \/* Remove duplicates from linked list *\/<br\/>    res = SortedMerge(a, b);<br\/> <br\/>    printf(&quot;Merged Linked List is: \\n&quot;);<br\/>    printList(res);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p><strong>Output :<\/strong><\/p>\n<pre>Merged Linked List is: \r\n2 3 5 10 15 20 \r\n<\/pre>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 2 (Using Local References)<\/strong><br \/>\nThis solution is structurally very similar to the above, but it avoids using a dummy node. Instead, it maintains a struct node** pointer, lastPtrRef, that always points to the last pointer of the result list. This solves the same case that the dummy node did \u2014 dealing with the result list when it is empty. If you are trying to build up a list at its tail, either the dummy node or the struct node** \u201creference\u201d strategy can be used (see Section 1 for details).<\/p>\n<div><strong>\u00a0C Programming:<\/strong><\/div>\n<div>\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\">struct node* SortedMerge(struct node* a, struct node* b) <br\/>{<br\/>  struct node* result = NULL;<br\/>   <br\/>  \/* point to the last result pointer *\/<br\/>  struct node** lastPtrRef = &amp;result; <br\/>   <br\/>  while(1) <br\/>  {<br\/>    if (a == NULL) <br\/>    {<br\/>      *lastPtrRef = b;<br\/>       break;<br\/>    }<br\/>    else if (b==NULL) <br\/>    {<br\/>       *lastPtrRef = a;<br\/>       break;<br\/>    }<br\/>    if(a-&gt;data &lt;= b-&gt;data) <br\/>    {<br\/>      MoveNode(lastPtrRef, &amp;a);<br\/>    }<br\/>    else<br\/>    {<br\/>      MoveNode(lastPtrRef, &amp;b);<br\/>    }<br\/>   <br\/>    \/* tricky: advance to point to the next &quot;.next&quot; field *\/<br\/>    lastPtrRef = &amp;((*lastPtrRef)-&gt;next); <br\/>  }<br\/>  return(result);<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<p><strong>Method 3 (Using Recursion)<\/strong><br \/>\nMerge is one of those nice recursive problems where the recursive solution code is much cleaner than the iterative code. You probably wouldn\u2019t want to use the recursive version for production code however, because it will use stack space which is proportional to the length of the lists.<\/p>\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\">struct node* SortedMerge(struct node* a, struct node* b) <br\/>{<br\/>  struct node* result = NULL;<br\/> <br\/>  \/* Base cases *\/<br\/>  if (a == NULL) <br\/>     return(b);<br\/>  else if (b==NULL) <br\/>     return(a);<br\/> <br\/>  \/* Pick either a or b, and recur *\/<br\/>  if (a-&gt;data &lt;= b-&gt;data) <br\/>  {<br\/>     result = a;<br\/>     result-&gt;next = SortedMerge(a-&gt;next, b);<br\/>  }<br\/>  else<br\/>  {<br\/>     result = b;<br\/>     result-&gt;next = SortedMerge(a, b-&gt;next);<br\/>  }<br\/>  return(result);<br\/>}<\/code><\/pre> <\/div>\n[ad type=&#8221;banner&#8221;]\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>C Algorithm &#8211; Merge two sorted linked lists &#8211; Linked List &#8211; Write a SortedMerge() function that takes two lists, each of which is sorted in increasing order<\/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":[72394,81476,81477,81474,81479,81478,81483,81475,81482,81481,81480,81484],"class_list":["post-27368","post","type-post","status-publish","format-standard","hentry","category-linked-list","category-singly-linked-list","tag-bubble-sort-linked-list-c","tag-merge-sort-linked-list-c","tag-merge-two-sorted-array","tag-merge-two-sorted-linked-lists-python","tag-merge-two-sorted-lists-python","tag-merge-two-unsorted-linked-lists","tag-merge-two-unsorted-linked-lists-in-c","tag-merging-of-linked-list-in-data-structure","tag-sort-linked-list-in-c","tag-sorted-linked-list-c","tag-sorted-linked-list-java","tag-sorting-a-singly-linked-list-in-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27368","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=27368"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27368\/revisions"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27368"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27368"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27368"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}