-
Notifications
You must be signed in to change notification settings - Fork 16
/
MergeSortedLinkedlist.cpp
117 lines (90 loc) · 1.75 KB
/
MergeSortedLinkedlist.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
#include <iostream>
using namespace std;
struct Node
{
int key;
struct Node *next;
};
Node *reverseList(Node *head)
{
if (head->next == NULL)
return head;
Node *rest = reverseList(head->next);
head->next->next = head;
head->next = NULL;
return rest;
}
Node *sortedMerge(Node *a, Node *b)
{
a = reverseList(a);
b = reverseList(b);
Node *head = NULL;
Node *temp;
while (a != NULL && b != NULL)
{
if (a->key >= b->key)
{
temp = a->next;
a->next = head;
head = a;
a = temp;
}
else
{
temp = b->next;
b->next = head;
head = b;
b = temp;
}
}
while (a != NULL)
{
temp = a->next;
a->next = head;
head = a;
a = temp;
}
while (b != NULL)
{
temp = b->next;
b->next = head;
head = b;
b = temp;
}
return head;
}
void printList(struct Node *Node)
{
while (Node != NULL)
{
cout << Node->key << " ";
Node = Node->next;
}
}
Node *newNode(int key)
{
Node *temp = new Node;
temp->key = key;
temp->next = NULL;
return temp;
}
int main()
{
struct Node *res = NULL;
Node *a = newNode(5);
a->next = newNode(10);
a->next->next = newNode(15);
a->next->next->next = newNode(40);
Node *b = newNode(2);
b->next = newNode(3);
b->next->next = newNode(20);
cout << "List A before merge: \n";
printList(a);
cout << "\nList B before merge: \n";
printList(b);
/* merge 2 sorted Linked Lists */
res = sortedMerge(a, b);
cout << "\nMerged Linked List is: \n";
printList(res);
return 0;
}