-
Notifications
You must be signed in to change notification settings - Fork 0
/
aex.cpp
150 lines (136 loc) · 2.85 KB
/
aex.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
139
140
141
142
143
144
145
146
147
148
149
150
#include <iostream>
template < typename T > class LinkedList
{
private:
struct Node
{
T data;
Node *nex;
Node *pre;
Node(const T &data) : data(data), nex(nullptr), pre(nullptr) {}
};
Node *head;
Node *tail;
size_t len;
public:
LinkedList() : head(nullptr), tail(nullptr), len(0) {}
~LinkedList()
{
clear();
}
void clear()
{
Node *current = head;
while (current)
{
Node *next = current->nex;
delete current;
current = next;
}
head = tail = nullptr;
len = 0;
}
void push_back(const T &value)
{
Node *newNode = new Node(value);
if (!tail)
{
head = tail = newNode;
} else
{
tail->nex = newNode;
newNode->pre = tail;
tail = newNode;
}
++len;
}
// Split the list into two halves
Node *split(Node *head)
{
if (!head || !head->nex)
{
return head;
}
Node *slow = head;
Node *fast = head->nex;
while (fast && fast->nex)
{
slow = slow->nex;
fast = fast->nex->nex;
}
Node *mid = slow->nex;
slow->nex = nullptr;
return mid;
}
// Merge two sorted lists
Node *merge(Node *l1, Node *l2)
{
if (!l1)
return l2;
if (!l2)
return l1;
if (l1->data < l2->data)
{
l1->nex = merge(l1->nex, l2);
l1->nex->pre = l1;
l1->pre = nullptr;
return l1;
} else
{
l2->nex = merge(l1, l2->nex);
l2->nex->pre = l2;
l2->pre = nullptr;
return l2;
}
}
// Sort the list using merge sort algorithm
Node *merge_sort(Node *head)
{
if (!head || !head->nex)
{
return head;
}
Node *mid = split(head);
Node *left = merge_sort(head);
Node *right = merge_sort(mid);
return merge(left, right);
}
void sort()
{
head = merge_sort(head);
if (head)
{
tail = head;
while (tail->nex)
{
tail = tail->nex;
}
}
}
// Output the list
void print()
{
Node *current = head;
while (current)
{
std::cout << current->data << " ";
current = current->nex;
}
std::cout << std::endl;
}
};
int main()
{
LinkedList< int > list;
list.push_back(3);
list.push_back(1);
list.push_back(2);
list.push_back(4);
list.push_back(5);
std::cout << "Original list: ";
list.print();
list.sort();
std::cout << "Sorted list: ";
list.print();
return 0;
}