-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpp-data-structures-linked-list-concat.cpp
138 lines (110 loc) · 2.02 KB
/
cpp-data-structures-linked-list-concat.cpp
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
130
131
132
133
134
135
136
137
138
#include <iostream>
using namespace std;
struct Node {
int data; // data member
struct Node* next; // self-referencial member pointer
}
*first = NULL, * second = NULL , * third = NULL;
void create(int A[], int n) // creating a linked list from an array
{
int i;
struct Node* t, * last;
first = new Node;
first->data = A[0];
first->next = NULL;
last = first;
for (i = 1; i < n; i++)
{
t = new Node;
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
}void create2(int A[], int n) // creating a linked list from an array
{
int i;
struct Node* t, * last;
second = new Node;
second->data = A[0];
second->next = NULL;
last = second;
for (i = 1; i < n; i++)
{
t = new Node;
t->data = A[i];
t->next = NULL;
last->next = t;
last = t;
}
}
void Display(struct Node* p) // display the linked list elements
{
while (p != NULL)
{
cout << p->data << " ";
p = p->next;
}
cout << endl;
}
void Concat(struct Node* p, struct Node *q)
{
third = p;
while (p->next != NULL) // scan through first linked list
{
p = p->next;
}
p->next = q; // concat first linked list to 2nd list
}
void Merge(struct Node* p, struct Node* q) // merge and sort two linked lists
{
struct Node* last;
if (p->data < q->data)
{
third = last = p;
p = p->next;
third->next = NULL;
}
else
{
third = last = q;
q = q->next;
third->next = NULL;
}
while (p && q)
{
if (p->data < q->data)
{
last->next = p;
last = p;
p = p->next;
last->next = NULL;
}
else
{
last->next = q;
last = q;
q = q->next;
last->next = NULL;
}
}
if (p)
{
last->next = p;
}
if (q)
{
last->next = q;
}
}
int main() {
int A[] = { 1,5,5,7,9,11,11,13,15,16 };
create(A, 10);
int B[] = { 2,3,4,6 };
create2(B, 4);
Display(first);
Concat(first, second); // adds second onto end of first
Merge(first, second); // merges the two lists and sorts them
Display(third);
return 0;
}