This C Program finds the first common element between the 2 given linked list.
Here is a source code of the C Program to find the first common element between the 2 given linked list. The C program is successfully compiled and run on a Linux system. The program output is also shown below.
/*
* C Program to Find the first Common Element between the 2 given Linked Lists
*/
#include <stdio.h>
#include <stdlib.h>
struct node
{
int num;
struct node *next;
};
void create(struct node **);
int find(struct node *, struct node *);
void release(struct node **);
void display(struct node *);
int main()
{
struct node *p = NULL, *q = NULL;
int result;
printf("Enter data into the list\n");
create(&p);
printf("Enter data into the list\n");
create(&q);
printf("Displaying list1:\n");
display(p);
printf("Displaying list2:\n");
display(q);
result = find(p, q);
if (result)
{
printf("The first matched element is %d.\n", result);
}
else
{
printf("No matching element found.\n");
}
release (&p);
return 0;
}
int find(struct node *p, struct node *q)
{
struct node *temp;
while (p != NULL)
{
temp = q;
while (temp != NULL)
{
if (temp->num == p->num)
{
return p->num;
}
temp = temp->next;
}
p = p->next;
}
/*Assuming 0 is not used in the list*/
return 0;
}
void create(struct node **head)
{
int c, ch;
struct node *temp, *rear;
do
{
printf("Enter number: ");
scanf("%d", &c);
temp = (struct node *)malloc(sizeof(struct node));
temp->num = c;
temp->next = NULL;
if (*head == NULL)
{
*head = temp;
}
else
{
rear->next = temp;
}
rear = temp;
printf("Do you wish to continue [1/0]: ");
scanf("%d", &ch);
} while (ch != 0);
printf("\n");
}
void display(struct node *head)
{
while (head != NULL)
{
printf("%d\t", head->num);
head = head->next;
}
printf("\n");
}
void release(struct node **head)
{
struct node *temp;
while ((*head) != NULL)
{
temp = *head;
(*head) = (*head)->next;
free(temp);
}
}
$ cc firstcommon.c $ ./a.out Enter data into the list1 Enter number: 2 Do you wish to continue [1/0]: 1 Enter number: 8 Do you wish to continue [1/0]: 1 Enter number: 5 Do you wish to continue [1/0]: 1 Enter number: 6 Do you wish to continue [1/0]: 0 Enter data into the list2 Enter number: 3 Do you wish to continue [1/0]: 1 Enter number: 5 Do you wish to continue [1/0]: 1 Enter number: 9 Do you wish to continue [1/0]: 0 Displaying list1: 2 8 5 6 Displaying list2: 3 5 9 The first matched element is 5.
Sanfoundry Global Education & Learning Series – 1000 C Programs.
advertisement
Here’s the list of Best Books in C Programming, Data-Structures and Algorithms
If you wish to look at programming examples on all topics, go to C Programming Examples.
Related Posts:
- Practice Programming MCQs
- Check Computer Science Books
- Check Programming Books
- Practice Design & Analysis of Algorithms MCQ
- Apply for Computer Science Internship