{"id":27675,"date":"2018-04-09T20:21:00","date_gmt":"2018-04-09T14:51:00","guid":{"rendered":"https:\/\/www.wikitechy.com\/technology\/?p=27675"},"modified":"2018-09-14T18:59:05","modified_gmt":"2018-09-14T13:29:05","slug":"intersection-two-sorted-linked-lists","status":"publish","type":"post","link":"https:\/\/www.wikitechy.com\/technology\/intersection-two-sorted-linked-lists\/","title":{"rendered":"Intersection of two Sorted Linked Lists"},"content":{"rendered":"<p>Given two lists sorted in increasing order, create and return a new list representing the intersection of the two lists. The new list should be made with its own memory \u2014 the original lists should not be changed.<span id=\"more-7488\"><\/span><\/p>\n<p>For example, let the first linked list be 1-&gt;2-&gt;3-&gt;4-&gt;6 and second linked list be 2-&gt;4-&gt;6-&gt;8, then your function should create and return a third list as 2-&gt;4-&gt;6.<\/p>\n<div id=\"practice\"><strong>Method 1 (Using Dummy Node) <\/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. The 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 we are done, the result is in dummy.next.<\/div>\n<div><\/div>\n<div><strong>C 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\">#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/>  <br\/>\/* Link list node *\/<br\/>struct node<br\/>{<br\/>    int data;<br\/>    struct node* next;<br\/>};<br\/> <br\/>void push(struct node** head_ref, int new_data);<br\/> <br\/>\/*This solution uses the temporary dummy to build up the result list *\/<br\/>struct node* sortedIntersect(struct node* a, struct node* b)<br\/>{<br\/>  struct node dummy;<br\/>  struct node* tail = &amp;dummy;<br\/>  dummy.next = NULL;<br\/>  <br\/>  \/* Once one or the other list runs out -- we&#039;re done *\/<br\/>  while (a != NULL &amp;&amp; b != NULL)<br\/>  {<br\/>    if (a-&gt;data == b-&gt;data)<br\/>    {<br\/>       push((&amp;tail-&gt;next), a-&gt;data);<br\/>       tail = tail-&gt;next;<br\/>       a = a-&gt;next;<br\/>       b = b-&gt;next;<br\/>    }<br\/>    else if (a-&gt;data &lt; b-&gt;data) \/* advance the smaller list *\/     <br\/>       a = a-&gt;next;<br\/>    else<br\/>       b = b-&gt;next;<br\/>  }<br\/>  return(dummy.next);<br\/>}<br\/> <br\/>\/* UTILITY FUNCTIONS *\/<br\/>\/* Function to insert a node at the beginging of the 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 lists *\/<br\/>  struct node* a = NULL;<br\/>  struct node* b = NULL;<br\/>  struct node *intersect = NULL;<br\/>  <br\/>  \/* Let us create the first sorted linked list to test the functions<br\/>   Created linked list will be 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6 *\/<br\/>  push(&amp;a, 6);<br\/>  push(&amp;a, 5);<br\/>  push(&amp;a, 4);<br\/>  push(&amp;a, 3);<br\/>  push(&amp;a, 2);<br\/>  push(&amp;a, 1);                                   <br\/>  <br\/>  \/* Let us create the second sorted linked list <br\/>   Created linked list will be 2-&gt;4-&gt;6-&gt;8 *\/<br\/>  push(&amp;b, 8);<br\/>  push(&amp;b, 6);<br\/>  push(&amp;b, 4);<br\/>  push(&amp;b, 2);                                    <br\/>  <br\/>  \/* Find the intersection two linked lists *\/<br\/>  intersect = sortedIntersect(a, b);<br\/>  <br\/>  printf(&quot;\\n Linked list containing common items of a &amp; b \\n &quot;);<br\/>  printList(intersect);           <br\/>  <br\/>  getchar();<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively.<\/p>\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<\/p>\n<div>\n<div id=\"highlighter_214889\" class=\"syntaxhighlighter nogutter c\"><strong>C Programming:<\/strong><\/div>\n<div class=\"syntaxhighlighter nogutter c\">\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\">#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/>  <br\/>\/* Link list node *\/<br\/>struct node<br\/>{<br\/>    int data;<br\/>    struct node* next;<br\/>};<br\/> <br\/>void push(struct node** head_ref, int new_data);<br\/> <br\/>\/* This solution uses the local reference *\/<br\/>struct node* sortedIntersect(struct node* a, struct node* b)<br\/>{<br\/>  struct node* result = NULL;<br\/>  struct node** lastPtrRef = &amp;result;<br\/>  <br\/>  \/* Advance comparing the first nodes in both lists.<br\/>    When one or the other list runs out, we&#039;re done. *\/<br\/>  while (a!=NULL &amp;&amp; b!=NULL)<br\/>  {<br\/>    if (a-&gt;data == b-&gt;data)<br\/>    {<br\/>      \/* found a node for the intersection *\/<br\/>      push(lastPtrRef, a-&gt;data);<br\/>      lastPtrRef = &amp;((*lastPtrRef)-&gt;next);<br\/>      a = a-&gt;next;<br\/>      b = b-&gt;next;<br\/>    }<br\/>    else if (a-&gt;data &lt; b-&gt;data)<br\/>      a=a-&gt;next;       \/* advance the smaller list *\/   <br\/>    else   <br\/>      b=b-&gt;next;    <br\/>  }<br\/>  return(result);<br\/>}<br\/> <br\/>\/* UTILITY FUNCTIONS *\/<br\/>\/* Function to insert a node at the beginging of the 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 lists *\/<br\/>  struct node* a = NULL;<br\/>  struct node* b = NULL;<br\/>  struct node *intersect = NULL;<br\/>  <br\/>  \/* Let us create the first sorted linked list to test the functions<br\/>   Created linked list will be 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6 *\/<br\/>  push(&amp;a, 6);<br\/>  push(&amp;a, 5);<br\/>  push(&amp;a, 4);<br\/>  push(&amp;a, 3);<br\/>  push(&amp;a, 2);<br\/>  push(&amp;a, 1);                                   <br\/>  <br\/>  \/* Let us create the second sorted linked list <br\/>   Created linked list will be 2-&gt;4-&gt;6-&gt;8 *\/<br\/>  push(&amp;b, 8);<br\/>  push(&amp;b, 6);<br\/>  push(&amp;b, 4);<br\/>  push(&amp;b, 2);                                    <br\/>  <br\/>  \/* Find the intersection two linked lists *\/<br\/>  intersect = sortedIntersect(a, b);<br\/>  <br\/>  printf(&quot;\\n Linked list containing common items of a &amp; b \\n &quot;);<br\/>  printList(intersect);           <br\/>  <br\/>  getchar();<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively<\/p>\n<p><strong>Method 3 (Recursive)<\/strong><br \/>\nBelow is the recursive implementation of sortedIntersect().<\/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\">#include&lt;stdio.h&gt;<br\/>#include&lt;stdlib.h&gt;<br\/> <br\/>\/* Link list node *\/<br\/>struct node<br\/>{<br\/>    int data;<br\/>    struct node* next;<br\/>};<br\/> <br\/>struct node *sortedIntersect(struct node *a, struct node *b)<br\/>{<br\/>    \/* base case *\/<br\/>    if (a == NULL || b == NULL)<br\/>        return NULL;<br\/> <br\/>    \/* If both lists are non-empty *\/<br\/> <br\/>    \/* advance the smaller list and call recursively *\/<br\/>    if (a-&gt;data &lt; b-&gt;data)<br\/>        return sortedIntersect(a-&gt;next, b);<br\/> <br\/>    if (a-&gt;data &gt; b-&gt;data)<br\/>        return sortedIntersect(a, b-&gt;next);<br\/> <br\/>    \/\/ Below lines are executed only when a-&gt;data == b-&gt;data<br\/>    struct node *temp = (struct node *)malloc(sizeof(struct node));<br\/>    temp-&gt;data = a-&gt;data;<br\/> <br\/>    \/* advance both lists and call recursively *\/<br\/>    temp-&gt;next = sortedIntersect(a-&gt;next, b-&gt;next);<br\/>    return temp;<br\/>}<br\/> <br\/>\/* UTILITY FUNCTIONS *\/<br\/>\/* Function to insert a node at the beginging of the linked list *\/<br\/>void push(struct node** head_ref, int new_data)<br\/>{<br\/>    \/* allocate node *\/<br\/>    struct node* new_node = (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 lists *\/<br\/>    struct node* a = NULL;<br\/>    struct node* b = NULL;<br\/>    struct node *intersect = NULL;<br\/> <br\/>    \/* Let us create the first sorted linked list to test the functions<br\/>     Created linked list will be 1-&gt;2-&gt;3-&gt;4-&gt;5-&gt;6 *\/<br\/>    push(&amp;a, 6);<br\/>    push(&amp;a, 5);<br\/>    push(&amp;a, 4);<br\/>    push(&amp;a, 3);<br\/>    push(&amp;a, 2);<br\/>    push(&amp;a, 1);<br\/> <br\/>    \/* Let us create the second sorted linked list<br\/>     Created linked list will be 2-&gt;4-&gt;6-&gt;8 *\/<br\/>    push(&amp;b, 8);<br\/>    push(&amp;b, 6);<br\/>    push(&amp;b, 4);<br\/>    push(&amp;b, 2);<br\/> <br\/>    \/* Find the intersection two linked lists *\/<br\/>    intersect = sortedIntersect(a, b);<br\/> <br\/>    printf(&quot;\\n Linked list containing common items of a &amp; b \\n &quot;);<br\/>    printList(intersect);<br\/> <br\/>    return 0;<br\/>}<\/code><\/pre> <\/div>\n<p>Time Complexity: O(m+n) where m and n are number of nodes in first and second linked lists respectively.<\/p>\n<div id=\"company_tags\"><\/div>\n<\/div>\n<\/div>\n<\/div>\n","protected":false},"excerpt":{"rendered":"<p>Intersection of two Sorted Linked Lists &#8211; Linked List &#8211; Given two lists sorted in increasing order, create and return a new list representing <\/p>\n","protected":false},"author":1,"featured_media":31273,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[79476,79478],"tags":[81968,81685,81966,81687,81688,81686,81691,81694,81969,81692,81967,81690,81689],"class_list":["post-27675","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-linked-list","category-singly-linked-list","tag-guava-intersection","tag-intersection-of-two-linked-lists-c","tag-intersection-of-two-linked-lists-java","tag-intersection-of-two-linked-lists-python","tag-intersection-of-two-lists-java","tag-intersection-of-two-sorted-linked-lists-java","tag-java-8-list-intersection","tag-java-difference-of-two-lists","tag-java-intersect-rectangle","tag-java-intersection-of-two-arrays","tag-java-list-retainall-example","tag-union-and-intersection-of-two-linked-lists-in-java","tag-union-and-intersection-of-two-linked-lists-using-c"],"_links":{"self":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27675","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=27675"}],"version-history":[{"count":0,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/posts\/27675\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media\/31273"}],"wp:attachment":[{"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/media?parent=27675"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/categories?post=27675"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.wikitechy.com\/technology\/wp-json\/wp\/v2\/tags?post=27675"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}