blob: efdb939a03bd80ae400f9bea4cbc7536cc603247 (
plain)
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
|
#include<iostream>
using namespace std;
template<typename T>
struct node {
T value;
node<T>* next;
};
template<class T>
class stack {
public:
stack() : _head{nullptr} {}
~stack() {
auto iter = _head;
while(iter) {
delete iter;
iter = iter->next;
}
}
stack<T>* push(T val) {
if(!_head) {
_head = new node<T>{val, nullptr};
} else {
_head = new node<T>{val, _head};
}
return this;
}
stack<T>* pop() {
if(!_head) return this;
auto old_head = _head;
_head = _head->next;
delete old_head;
return this;
}
void print() {
auto iter = _head;
while(iter) {
cout << iter->value << ' ';
iter = iter->next;
}
cout << endl;
}
private:
node<T>* _head;
};
int main() {
stack<int>* s = new stack<int>();
s->pop();
s->push(4)->push(2)->push(8);
s->pop();
s->push(1);
s->print();
delete s;
return 0;
}
|