-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest2.cpp
More file actions
104 lines (90 loc) · 2.52 KB
/
test2.cpp
File metadata and controls
104 lines (90 loc) · 2.52 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
#include <iostream>
#include <stdexcept>
struct Node;
Node* Xor(Node* prev, Node* next) {
return reinterpret_cast<Node*>(reinterpret_cast<uintptr_t>(prev) ^ reinterpret_cast<uintptr_t>(next));
}
struct Node {
int val;
Node* diff;
Node(int val, Node* prev, Node* next) : val(val), diff(Xor(prev, next)) {}
Node* GetNext(Node* prev) {
return Xor(diff, prev);
}
Node* GetPrev(Node* next) {
return Xor(diff, next);
}
~Node() {
std::cout << "Deleting Node with value " << val << std::endl; // Testing for memory leaks
}
};
void Add(Node* &head, int val) {
if (nullptr == head) {
head = new Node(val, nullptr, nullptr);
return;
}
Node* prev = nullptr;
Node* cur = head;
Node* next = cur->GetNext(prev);
while (next != nullptr) {
prev = cur;
cur = next;
next = cur->GetNext(prev);
}
cur->diff = Xor(prev, new Node(val, cur, nullptr));
}
int Get(Node* cur, int index) {
Node* prev = nullptr;
while (index && cur != nullptr) {
Node* next = cur->GetNext(prev);
prev = cur;
cur = next;
--index;
}
if (index != 0) {
throw std::out_of_range("index out of range");
}
return cur->val;
}
void Delete(Node* cur) {
Node* prev = nullptr;
while (cur != nullptr) {
Node* next = cur->GetNext(prev);
delete prev;
prev = cur;
cur = next;
}
delete prev;
}
std::ostream &operator<<(std::ostream &os, Node* cur) {
os << '[';
Node* prev = nullptr;
while (cur != nullptr) {
os << cur->val << ", ";
Node* next = cur->GetNext(prev);
prev = cur;
cur = next;
}
os << ']';
return os;
}
int main() {
Node* head = nullptr;
Add(head, 1000);
Add(head, 100);
Add(head, 10);
Add(head, 1);
std::cout << head << std::endl;
std::cout << Get(head, 2) << std::endl;
using somefunc = void(*)(int, int); // function pointer syntax
somefunc f = [] (int a, int b) { std::cout << a << ", " << b << std::endl; }; // lambda
f(1, 2);
auto k = [&] (int i) -> int { return Get(head, i); }; // Type is int(*)(int)
std::cout << k(1) << std::endl;
int i = 0, j = 0;
// auto l = [&, i] () { std::cout << ++i << ", " << ++j << std::endl; }; l(); // Error; cannot modify i
// auto m = [=, &i] () { std::cout << ++i << ", " << ++j << std::endl; }; m(); // Error; cannot modify j
std::cout << ++i << ", " << ++j << std::endl;
Delete(head);
return 0;
}