C program concatenate two linked lists.
PROGRAM:
#include <stdio.h>#include <stdlib.h>
//Creating structure
struct node
{
int data;
struct node *link;
};
struct node * create(struct node *);
void disp(struct node *);
struct node * concat(struct node *,struct node *);
//main function
int main()
{
struct node *first1=NULL;
struct node *first2=NULL;
printf("\nEnter first linked list:\n");
first1=create(first1);
printf("\nLinked list 1 created!\n");
disp(first1);
printf("\nEnter second linked list:\n");
first2=create(first2);
printf("\nLinked list 2 created!\n");
disp(first2);
first1=concat(first1,first2);
printf("\n\nConcatenated Linked Lists\n");
disp(first1);
return 0;
}
//function to create linked list
struct node * create(struct node *first)
{
struct node *new_node;
int choice=0;
do
{
new_node=(struct node *)malloc(sizeof(struct node));
printf("\nEnter an element\n");
scanf("%d",&new_node->data);
new_node->link=NULL;
if(first==NULL)
first=new_node;
else
{
new_node->link=first;
first=new_node;
}
printf("\nEnter 1 to continue, 0 to stop\n");
scanf("%d",&choice);
}while(choice==1);
return first;
}
//function to display linked list
void disp(struct node *first)
{
struct node *temp;
if(first==NULL)
printf("\nDisplay not possible, Linked list empty\n");
else if(first->link==NULL)
{
printf("Displaying linked list elements:\n");
printf("%d",first->data);
}
else
{
printf("Displaying linked list elements:\n");
temp=first;
while(temp!=NULL)
{
printf("%d\t",temp->data);
temp=temp->link;
}
}
}
//function to concatenate two linked lists
struct node * concat(struct node * first1,struct node *first2)
{
struct node *temp=first1;
while(temp->link!=NULL)
temp=temp->link;
temp->link=first2;
return first1;
}
OUTPUT:
Enter first linked list:Enter an element
10
Enter 1 to continue, 0 to stop
1
Enter an element
20
Enter 1 to continue, 0 to stop
1
Enter an element
30
Enter 1 to continue, 0 to stop
1
Enter an element
40
Enter 1 to continue, 0 to stop
1
Enter an element
50
Enter 1 to continue, 0 to stop
0
Linked list 1 created!
Displaying linked list elements:
50 40 30 20 10
Enter second linked list:
Enter an element
100
Enter 1 to continue, 0 to stop
1
Enter an element
200
Enter 1 to continue, 0 to stop
1
Enter an element
300
Enter 1 to continue, 0 to stop
1
Enter an element
400
Enter 1 to continue, 0 to stop
1
Enter an element
500
Enter 1 to continue, 0 to stop
0
Linked list 2 created!
Displaying linked list elements:
500 400 300 200 100
Concatenated Linked Lists
Displaying linked list elements:
50 40 30 20 10 500 400 300 200 100