-
Notifications
You must be signed in to change notification settings - Fork 1
/
7_1_sorted_merge.cpp
108 lines (100 loc) · 2.01 KB
/
7_1_sorted_merge.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
#include <iostream>
using namespace std;
template <class T>
class LinkedList
{
struct node
{
T x;
node *next;
};
public:
node *head;
node *curr;
LinkedList()
{
head = NULL;
curr = NULL;
}
void addValue(T a)
{
node *n = new node;
n->x = a;
n->next = head;
head = n;
if(curr == NULL)
curr = head;
}
void rewind()
{
curr = head;
}
void next()
{
if( curr != NULL )
curr = curr->next;
}
int getValue()
{
if( curr != NULL )
return curr->x;
return 0;
}
int hasValue()
{
return ( curr != NULL ? true : false );
}
void function(struct node* b)
{
sortMerge(head,b);
rewind();
}
void sortMerge(struct node* a, struct node* b)
{
node *temp = new node;
if(a==NULL && b!=NULL)
a->next = b;
else if(a!=NULL && b!=NULL)
{
if(a->x <= b->x)
{
if(a->next==NULL)
a->next = b;
else
sortMerge(a->next,b);
}
else
{
temp->x = a->x;
temp->next = a->next;
a->x = b->x;
a->next = b->next;
sortMerge(a,temp);
}
}
}
};
int main()
{
LinkedList<int> L, M;
L.addValue(12);
L.addValue(10);
L.addValue(9);
L.addValue(7);
L.addValue(5);
L.addValue(2);
M.addValue(11);
M.addValue(8);
M.addValue(4);
M.addValue(3);
M.addValue(1);
L.rewind();
M.rewind();
L.function(M.head);
while(L.hasValue())
{
cout << "Value: " << L.getValue() << endl;
L.next();
}
return 0;
}