-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merge two unsorted linked list
119 lines (92 loc) · 1.59 KB
/
Merge two unsorted 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
110
111
112
113
114
115
116
117
118
119
#include <bits/stdc++.h>
using namespace std;
struct node {
int data;
node* next;
};
void setData(node* head)
{
node* tmp;
tmp = head;
while (tmp != NULL) {
cout << tmp->data
<< " -> ";
tmp = tmp->next;
}
}
node* getData(node* head, int num)
{
node* temp = new node;
node* tail = head;
temp->data = num;
temp->next = NULL;
if (head == NULL) {
head = temp;
tail = temp;
}
else {
while (tail != NULL) {
if (tail->next == NULL) {
tail->next = temp;
tail = tail->next;
}
tail = tail->next;
}
}
return head;
}
node* mergelists(node** head1,
node** head2)
{
node* tail = *head1;
while (tail != NULL) {
if (tail->next == NULL
&& head2 != NULL) {
tail->next = *head2;
break;
}
tail = tail->next;
}
return *head1;
}
void sortlist(node** head1)
{
node* curr = *head1;
node* temp = *head1;
while (curr->next != NULL) {
temp = curr->next;
while (temp != NULL) {
if (temp->data < curr->data) {
int t = temp->data;
temp->data = curr->data;
curr->data = t;
}
temp = temp->next;
}
curr = curr->next;
}
}
int main()
{
node* head1 = new node;
node* head2 = new node;
head1 = NULL;
head2 = NULL;
// Given Linked List 1
head1 = getData(head1, 4);
head1 = getData(head1, 7);
head1 = getData(head1, 5);
// Given Linked List 2
head2 = getData(head2, 2);
head2 = getData(head2, 1);
head2 = getData(head2, 8);
head2 = getData(head2, 1);
// Merge the two lists
// in a single list
head1 = mergelists(&head1,
&head2);
// Sort the unsorted merged list
sortlist(&head1);
setData(head1);
return 0;
}