-
Notifications
You must be signed in to change notification settings - Fork 67
/
Copy patha program to merge two sorted linked list
109 lines (87 loc) · 1.19 KB
/
a program to merge two sorted linked list
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
#include<stdio.h>
#include<conio.h>
#include<alloc.h>
typedef struct linked
{
int val;
struct linked *next;
}lnk;
lnk *create();
lnk *merge(lnk *,lnk *);
void disp(lnk *);
void main()
{
lnk *h1,*h2,*h;
printf("\n\nEnter the values (0 to exit) : ");
h1=create();
printf("\n\nEnter the values (0 to exit) : ");
h2=create();
printf("\n\nValues in the first linked list are : ");
disp(h1);
printf("\n\nValues in the second linked list are : ");
disp(h2);
h=merge(h1,h2);
printf("\n\nValues in the merged linked list are : ");
disp(h);
getch();
}
lnk *create()
{
lnk *temp,*ptr,*h=NULL;
int v;
while(1)
{
scanf("%d",&v);
if(v==0)
return h;
temp=(lnk*)malloc(sizeof(lnk));
temp->val=v;
temp->next=NULL;
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
}
}
void disp(lnk *h)
{
while(h!=NULL)
{
printf("%d",h->val);
h=h->next;
}
}
lnk *merge(lnk *h1,lnk *h2)
{
lnk *h=NULL,*temp,*ptr;
while(h1!=NULL && h2!=NULL)
{
if(h1->val<h2->val)
{
temp=h1;
h1=h1->next;
}
else if(h2->val<h1->val)
{
temp=h2;
h2=h2->next;
}
else
{
temp=h1;
h1=h1->next;
h2=h2->next;
}
if(h==NULL)
h=temp;
else
ptr->next=temp;
ptr=temp;
}
if(h1!=NULL && h2==NULL)
ptr->next=h1;
if(h2!=NULL && h1==NULL)
ptr->next=h2;
return h;
}