source:
doc/generic_types/evaluation/cpp-stack.hpp
@
e50e9ff
Last change on this file since e50e9ff was 6a8ac0b, checked in by , 7 years ago | |
---|---|
|
|
File size: 1.1 KB |
Rev | Line | |
---|---|---|
[d919f47] | 1 | #pragma once |
[309be81] | 2 | #include <utility> |
3 | ||
4 | template<typename T> class stack { | |
5 | struct node { | |
6 | T value; | |
7 | node* next; | |
8 | ||
[c87cd93] | 9 | node( const T& v, node* n = nullptr ) : value(v), next(n) {} |
[309be81] | 10 | }; |
11 | node* head; | |
12 | ||
[122aecd] | 13 | void copy(const stack<T>& o) { |
14 | node** crnt = &head; | |
[6a8ac0b] | 15 | for ( node* next = o.head; next; next = next->next ) { |
[3fb7f5e] | 16 | *crnt = new node{ next->value }; /***/ |
[122aecd] | 17 | crnt = &(*crnt)->next; |
18 | } | |
19 | *crnt = nullptr; | |
20 | } | |
21 | public: | |
22 | void clear() { | |
[6a8ac0b] | 23 | for ( node* next = head; next; ) { |
[309be81] | 24 | node* crnt = next; |
25 | next = crnt->next; | |
26 | delete crnt; | |
27 | } | |
[0d10090] | 28 | head = nullptr; |
[309be81] | 29 | } |
30 | ||
[122aecd] | 31 | stack() : head(nullptr) {} |
32 | stack(const stack<T>& o) { copy(o); } | |
33 | stack(stack<T>&& o) : head(o.head) { o.head = nullptr; } | |
34 | ~stack() { clear(); } | |
35 | ||
36 | stack& operator= (const stack<T>& o) { | |
37 | if ( this == &o ) return *this; | |
38 | clear(); | |
39 | copy(o); | |
[b276be5] | 40 | return *this; |
[122aecd] | 41 | } |
42 | ||
43 | stack& operator= (stack<T>&& o) { | |
44 | if ( this == &o ) return *this; | |
45 | head = o.head; | |
46 | o.head = nullptr; | |
47 | return *this; | |
48 | } | |
49 | ||
[a381b46] | 50 | bool empty() const { return head == nullptr; } |
[309be81] | 51 | |
[c87cd93] | 52 | void push(const T& value) { head = new node{ value, head }; /***/ } |
[309be81] | 53 | |
54 | T pop() { | |
55 | node* n = head; | |
56 | head = n->next; | |
57 | T x = std::move(n->value); | |
58 | delete n; | |
59 | return x; | |
60 | } | |
61 | }; |
Note: See TracBrowser
for help on using the repository browser.