Skip to content

Commit 0fb432f

Browse files
Create Merging_two_Singly_Linked_List.c
1 parent 6ef5516 commit 0fb432f

File tree

1 file changed

+84
-0
lines changed

1 file changed

+84
-0
lines changed

Merging_two_Singly_Linked_List.c

+84
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
// Write a C Program to Merge two Singly Linked List and Display the elements of Merged List.
2+
3+
// Input:
4+
5+
// Number of Elements in List1 - m
6+
7+
// m Elements in List1
8+
9+
// Number of Elements in List2 - n
10+
11+
// n Elements in List2
12+
13+
// Output:
14+
15+
// m+n Elements from List1 and List2
16+
17+
#include<stdio.h>
18+
#include<stdlib.h>
19+
struct node
20+
{
21+
int element;
22+
struct node *next;
23+
};
24+
typedef struct node node;
25+
node *position;
26+
void insert(node *list,int e)
27+
{
28+
node *newnode=malloc(sizeof(node));
29+
newnode->element=e;
30+
if(list->next==NULL)
31+
{
32+
list->next=newnode;
33+
newnode->next=NULL;
34+
position=newnode;
35+
}
36+
else
37+
{
38+
newnode->next=NULL;
39+
position->next=newnode;
40+
position=newnode;
41+
}
42+
}
43+
void merge(node *list1,node *list2)
44+
{
45+
node *position=list1;
46+
while(position->next!=NULL)
47+
position=position->next;
48+
position->next=list2->next;
49+
}
50+
void display(node *list1)
51+
{
52+
if(list1->next!=NULL)
53+
{
54+
node *position=list1->next;
55+
while(position!=NULL)
56+
{
57+
printf("%d\n",position->element);
58+
position=position->next;
59+
}
60+
}
61+
}
62+
int main()
63+
{
64+
int n,e,m;
65+
node *list1=malloc(sizeof(node));
66+
list1->next=NULL;
67+
node *list2=malloc(sizeof(node));
68+
list2->next=NULL;
69+
scanf("%d",&n);
70+
for(int i=0;i<n;i++)
71+
{
72+
scanf("%d",&e);
73+
insert(list1,e);
74+
}
75+
scanf("%d",&m);
76+
for(int i=0;i<m;i++)
77+
{
78+
scanf("%d",&e);
79+
insert(list2,e);
80+
}
81+
merge(list1,list2);
82+
display(list1);
83+
return 0;
84+
}

0 commit comments

Comments
 (0)