# C program to compare two linked lists

In this tutorial, we will learn how to compare two linked lists using the C program? By Nidhi Last updated : August 02, 2023

## Problem statement

Create two linked lists, compare both lists and print the result.

## C program to compare two linked lists

The source code to compare two linked lists is given below. The given program is compiled and executed using GCC compile on UBUNTU 18.04 OS successfully.

```// C program to compare two linked lists

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

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

typedef struct
{
Node* tail;

} List;

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

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

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

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

return nNode;
}

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

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

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

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

//To print 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");
}

int compareLists(List* lp1, List* lp2)
{
Node* temp1;
Node* temp2;
int flag = 1;

while (temp1 != NULL && temp2 != NULL) {
if (temp1->item != temp2->item) {
flag = 0;
break;
}
temp1 = temp1->next;
temp2 = temp2->next;
}

return flag;
}

//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);

if (compareLists(lp1, lp2))
printf("Both lists are same\n");
else
printf("Lists are different\n");

return 0;
}
```

## Output

```List1:
| 00500 |--->| 00400 |--->| 00300 |--->| 00100 |--->| 00200 |

List2:
| 00500 |--->| 00400 |--->| 00300 |--->| 00100 |--->| 00200 |

Both lists are same
```

## Explanation

In the above program, 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, a function compareLists() to compare linked lists. The compareLists() function return 1 if both lists are the same otherwise it will return 0.

In the main() function, we created two linked lists. Then we compared both lists using compareLists() function and printed the appropriate message on the console screen.