-
Notifications
You must be signed in to change notification settings - Fork 1
/
Concatenating_and_merging_two_linked_lists.c
129 lines (128 loc) · 2.93 KB
/
Concatenating_and_merging_two_linked_lists.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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#include <stdio.h>
#include <stdlib.h>
struct node
{
int data;
struct node *next;
} *first = NULL, *second = NULL, *third = NULL;
void create_first(int A[], int n)
{
first = (struct node *)malloc(sizeof(struct node));
(*(first)).data = A[0];
(*(first)).next = NULL;
struct node *t, *last;
last = first;
for (int i = 1; i < n; i++)
{
t = (struct node *)malloc(sizeof(struct node));
(*(t)).data = A[i];
(*(t)).next = NULL;
(*(last)).next = t;
last = t;
}
}
void create_second(int A[], int n)
{
second = (struct node *)malloc(sizeof(struct node));
(*(second)).data = A[0];
(*(second)).next = NULL;
struct node *t, *last;
last = second;
for (int i = 1; i < n; i++)
{
t = (struct node *)malloc(sizeof(struct node));
(*(t)).data = A[i];
(*(t)).next = NULL;
(*(last)).next = t;
last = t;
}
}
void display(struct node *p)
{
while (p != NULL)
{
printf("%d\t", (*(p)).data);
p = (*(p)).next;
}
}
struct node *concatenate(struct node *p, struct node *q)
{
struct node *a;
a = p;
while ((*(a)).next != NULL)
{
a = (*(a)).next;
}
(*(a)).next = q;
q = NULL;
return p;
}
struct node *merge(struct node *p, struct node *q)
{
struct node *last = NULL;
if ((*(p)).data < (*(q)).data)
{
third = last = p;
p = (*(p)).next;
(*(last)).next = NULL;
}
else if ((*(q)).data < (*(p)).data)
{
third = last = q;
q = (*(q)).next;
(*(last)).next = NULL;
}
while (p != NULL && q != NULL)
{
if ((*(p)).data < (*(q)).data)
{
(*(last)).next = p;
last = p;
p = (*(p)).next;
(*(last)).next = NULL;
}
else if ((*(q)).data < (*(p)).data)
{
(*(last)).next = q;
last = q;
q = (*(q)).next;
(*(last)).next = NULL;
}
}
if (p != NULL)
{
while (p != NULL)
{
(*(last)).next = p;
last = p;
p = (*(p)).next;
(*(last)).next = NULL;
}
}
if (q != NULL)
{
while (q != NULL)
{
(*(last)).next = q;
last = q;
q = (*(q)).next;
(*(last)).next = NULL;
}
}
return third;
}
int main()
{
int A[8] = {1, 3, 5, 7, 9, 11, 13, 15};
int B[5] = {2, 4, 6, 8, 10};
create_first(A, 8);
printf("First linked list is:\n");
display(first);
create_second(B, 5);
printf("\nSecond linked list is:\n");
display(second);
// printf("\nConcatenated linked list is:\n");
// display(concatenate(first, second));
printf("\nMerged Linked list is:\n");
display(merge(first, second));
}