-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmerge_2_linklist.c
113 lines (107 loc) · 2.36 KB
/
merge_2_linklist.c
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
110
111
112
113
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
};
struct node *createlinklist(int n);
struct node *merge_two_linklist(struct node *head1,struct node *head2);
void display(struct node *head);
int main()
{
int n1,n2;
struct node *head1 = NULL;
struct node *head2 = NULL;
struct node *head3 = NULL;
printf("Enter how many nodes: ");
scanf("%d", &n1);
head1 = createlinklist(n1);
display(head1);
printf("Enter how many nodes: ");
scanf("%d", &n2);
printf("\n");
head2 = createlinklist(n2);
display(head2);
printf("\n");
head1 = merge_two_linklist(head1,head2);
display(head1);
return 0;
}
struct node *createlinklist(int n)
{
struct node *head = NULL;
struct node *temp = NULL;
struct node *p = NULL;
for (int i = 0; i < n; i++)
{
temp = (struct node *)malloc(sizeof(struct node));
temp->next = NULL;
printf("Enter data: ");
scanf("%d", &temp->data);
if (head == NULL)
{
head = temp;
}
else
{
p = head;
while (p->next != NULL)
{
p = p->next;
}
p->next = temp;
}
}
return head;
}
void display(struct node *head)
{
struct node *p = head;
while (p != NULL)
{
printf("%d->", p->data);
p = p->next;
}
printf("NULL\n");
}
struct node *merge_two_linklist(struct node *head1,struct node *head2){
struct node *p=head1;
struct node *q=head2;
struct node *head3;
struct node *s;
if (p->data>q->data)
{
head3=s=q;
q=q->next;
}
else
{
head3=s=p;
p=p->next;
}
while (p!=NULL && q!=NULL)
{
if (p->data>q->data)
{
s->next=q;
s=q;
q=q->next;
}
else
{
s->next=p;
s=p;
p=p->next;
}
if (p==NULL)
{
s->next=q;
}
if(q==NULL)
{
s->next=p;
}
}
return head3;
}