-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsparse_linked_list.cpp
More file actions
118 lines (98 loc) · 2.69 KB
/
sparse_linked_list.cpp
File metadata and controls
118 lines (98 loc) · 2.69 KB
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
#include <iostream>
using namespace std;
struct sparse_linked_list {
// тип значений
typedef int value_type;
struct node {
size_t index;
value_type value;
node *next;
node(size_t index, value_type value) {
this->index = index;
this->value = value;
next = nullptr;
}
};
// якщо потрібно підтримувати розмір, розкоментуйте всі його згадування
// size_t size;
node *begin, *end;
sparse_linked_list() {
// size = 0;
begin = nullptr;
end = nullptr;
}
//! push_back не дивиться на порядок індексів
//! краще використовувати insert
void push_back(size_t index, value_type value) {
node *node_new = new node(index, value);
if (empty()) {
begin = node_new;
} else {
end->next = node_new;
}
end = node_new;
// size++;
}
// поверає false, якщо індекс зайнятий
bool insert(size_t index, value_type value) {
if (empty()) {
node *node_new = new node(index, value);
begin = node_new;
end = node_new;
return true;
}
if (index == end->index) {
return false;
}
if (index > end->index) {
push_back(index, value);
return true;
}
for (auto *i = begin; i != nullptr; i = i->next) {
if (index == i->index) {
return false;
}
if (index < i->index) {
node *node_new = new node(i->index, i->value);
node_new->next = i->next;
i->index = index;
i->value = value;
i->next = node_new;
if (end == i) {
end = node_new;
}
return true;
}
}
throw "How did u get here?";
}
bool empty() {
return begin == nullptr;
}
~sparse_linked_list() {
node *i = begin;
while (i != nullptr) {
node *s = i;
i = i->next;
delete s;
}
}
};
int main() {
sparse_linked_list sll;
size_t n;
cin >> n;
for (size_t i = 0; i < n; i++) {
int a, b;
cin >> a >> b;
if (!sll.insert(a, b)) {
cout << "This index is used" << endl;
n++;
}
}
for (auto *i = sll.begin; i != nullptr; i = i->next) {
cout << i->index << '~' << i->value << ' ';
}
cout << endl;
return 0;
}