-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathSortLinkedListMethod1.cpp
103 lines (88 loc) · 2.1 KB
/
SortLinkedListMethod1.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
// Leetcode https://leetcode.com/explore/interview/card/top-interview-questions-hard/117/linked-list/840/
// Techie Deligt https://www.techiedelight.com/given-linked-list-change-sorted-order/
// n^2 method
#include <iostream>
#include <vector>
class LinkedList
{
private:
class Node
{
public:
int key;
Node* next;
Node() : key(0), next(nullptr) { }
Node(int k) : key(k), next(nullptr) { }
};
Node* head;
Node* sortedInsert(Node* head, Node* node)
{
Node* dummy = new Node();
Node* current = dummy;
dummy->next = head;
while (current->next != nullptr && current->next->key < node->key) {
current = current->next;
}
node->next = current->next;
current->next = node;
return dummy->next;
}
public:
LinkedList() : head(nullptr) { }
~LinkedList()
{
Node* current = head;
while (current != nullptr) {
Node* temp = current;
current = current->next;
delete temp;
}
head = nullptr;
}
void push(int val)
{
Node* node = new Node(val);
if (head != nullptr) {
node->next = head;
}
head = node;
}
void createListFromVector(std::vector<int>& keys)
{
for (auto key : keys) {
push(key);
}
}
void print()
{
Node* current = head;
while (current != nullptr) {
std::cout << current->key << " ";
current = current->next;
}
std::cout << "\n";
}
void sort()
{
Node* current = head;
Node* next;
Node* result = nullptr;
while (current != nullptr) {
next = current->next;
result = sortedInsert(result, current);
current = next;
}
head = result;
}
};
int main()
{
std::vector<int> keys {6, 3, 4, 8, 2, 9, 10, 5, 1};
LinkedList list;
list.createListFromVector(keys);
list.print();
list.sort();
std::cout << "After sorting\n";
list.print();
return 0;
}