C program to find the first common element from the given linked lists

In this tutorial, we will learn how to find the first common element from the given linked lists using the C program? By Nidhi Last updated : August 02, 2023

Problem statement

Given two singly linked lists, we have to find the first common element from the given lists.

C program to find the first common element from the given linked lists

The source code to find the first common element from given linked lists is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

// C program to find the first common element
// from the given linked lists

#include <stdio.h>
#include <stdlib.h>

//Self-referential structure to create the node.
typedef struct tmp {
int item;
struct tmp* next;
} Node;

//structure for creating the linked list.
typedef struct
{
Node* tail;

} List;

//Initialize List
void initList(List* lp)
{
lp->tail = NULL;
}

//Create node and return the reference of it.
Node* createNode(int item)
{
Node* nNode;

nNode = (Node*)malloc(sizeof(Node));

nNode->item = item;
nNode->next = NULL;

return nNode;
}

//Add a new item at the end of the list.
{
Node* node;
node = createNode(item);

//if list is empty.
lp->tail = node;
}
else {
lp->tail->next = node;
lp->tail = lp->tail->next;
}
}

//Add a new item at beginning of the list.
{
Node* node;
node = createNode(item);

//if list is empty.
lp->tail = node;
}
else {
}
}

//To print the list from start to end of the list.
void printList(List* lp)
{
Node* node;

printf("\nEmpty List");
return;
}

while (node != NULL) {
printf("| %05d |", node->item);
node = node->next;

if (node != NULL)
printf("--->");
}
printf("\n\n");
}

void findFirstCommon(List* lp1, List* lp2)
{
Node* temp1;
Node* temp2;

int flag = 0;

while (temp1 != NULL) {
while (temp2 != NULL) {
if (temp1->item == temp2->item) {
printf("First Common Item is: %d\n", temp1->item);
flag = 1;
goto OUT;
}
temp2 = temp2->next;
}

temp1 = temp1->next;
}
OUT:
if (flag == 0)
printf("No common item found\n");
}

//Main function to execute program.
int main()
{
List* lp1;
List* lp2;

lp1 = (List*)malloc(sizeof(List));
lp2 = (List*)malloc(sizeof(List));

initList(lp1);
initList(lp2);

printf("List1:\n");
printList(lp1);

printf("List2:\n");
printList(lp2);

findFirstCommon(lp1, lp2);

return 0;
}

Output

List1:
| 00101 |--->| 00102 |--->| 00103 |--->| 00104 |--->| 00105 |

List2:
| 00201 |--->| 00202 |--->| 00103 |--->| 00204 |--->| 00205 |

First Common Item is: 103

Explanation

Here, we created a self-referential structure to implement a linked list, a function to add a node at the start and end of the list, and a function findFirstCommon() to find the first common item from two specified linked lists.

In the main() function, we created two linked lists and called the function findFirstCommon() to find the first common element.