struct node *sortedIntersect(struct node *a,struct node *b)
{
if(a==NULL ||b==NULL)
return ;
if(a->data<b->data)
 return sortedIntersect(a->next,b);
if(a->data>b->data)
return sortedIntersect(a,b->next);
struct node *temp=(struct node*)malloc (sizeof(struct node));
temp->data=a->data;
temp->next=sortedIntersect(a->next,b->next);
return temp;
}
Пример #2
0
//--------------------------------------------------------------------------------------------------
struct Node *sortedIntersect(struct Node *list1, struct Node *list2)
{
  if (list1 == NULL || list2 == NULL)                                                /* base case */
      return NULL;
  if (list1->data < list2->data)                 /* advance the smaller list and call recursively */
      return sortedIntersect(list1->next, list2);
  if (list1->data > list2->data)
      return sortedIntersect(list1, list2->next);
                                    // Below lines are executed only when list1->data == list2->data
  struct Node *temp = (struct Node *)malloc(sizeof(struct Node));
  temp->data = list1->data;
  temp->next = sortedIntersect(list1->next, list2->next); /*advance both lists and call recursively */
  return temp;
}
int main() {
	node* a = NULL;
  struct node* b = NULL;
  struct node *intersect = NULL;
  
  /* Let us create the first sorted linked list to test the functions
   Created linked list will be 1->2->3->4->5->6 */
  push(&a, 6);
  push(&a, 5);
  push(&a, 4);
  push(&a, 3);
  push(&a, 2);
  push(&a, 1);                                   
  
  /* Let us create the second sorted linked list 
   Created linked list will be 2->4->6->8 */
  push(&b, 8);
  push(&b, 6);
  push(&b, 4);
  push(&b, 2);                                    
  
  /* Find the intersection two linked lists */
  intersect = sortedIntersect(a, b);
  
  printf("\n Linked list containing common items of a & b \n ");
  printList(intersect); 
	return 0;
}
Пример #4
0
/* Drier program to test above functions*/
int main()
{
  /* Start with the empty lists */
  struct Node* list1 = NULL;
  struct Node* list2 = NULL;
  struct Node *intersect = NULL;
  
  /* Let us create the first sorted linked list to test the functions
   Created linked list will be 1->2->3->4->5->6 */
  push(&list1, 6);
  push(&list1, 5);
  push(&list1, 4);
  push(&list1, 3);
  push(&list1, 2);
  push(&list1, 1);                                   
  
  /* Let us create the second sorted linked list 
   Created linked list will be 2->4->6->8 */
  push(&list2, 8);
  push(&list2, 6);
  push(&list2, 4);
  push(&list2, 2);                                    
  
  /* Find the intersection two linked lists */
  intersect = sortedIntersect(list1, list2);
  
  printf("\n Linked list containing common items of list1 & list2 \n ");
  printList(intersect);           
  
  getchar();
}