source:
doc/generic_types/evaluation/cpp-stack.hpp
@
12d3187
Last change on this file since 12d3187 was c87cd93, checked in by , 8 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; | |
15 | node* next = o.head; | |
16 | while ( next ) { | |
[3fb7f5e] | 17 | *crnt = new node{ next->value }; /***/ |
[122aecd] | 18 | crnt = &(*crnt)->next; |
19 | next = next->next; | |
20 | } | |
21 | *crnt = nullptr; | |
22 | } | |
23 | public: | |
24 | void clear() { | |
[309be81] | 25 | node* next = head; |
26 | while ( next ) { | |
27 | node* crnt = next; | |
28 | next = crnt->next; | |
29 | delete crnt; | |
30 | } | |
[0d10090] | 31 | head = nullptr; |
[309be81] | 32 | } |
33 | ||
[122aecd] | 34 | stack() : head(nullptr) {} |
35 | stack(const stack<T>& o) { copy(o); } | |
36 | stack(stack<T>&& o) : head(o.head) { o.head = nullptr; } | |
37 | ~stack() { clear(); } | |
38 | ||
39 | stack& operator= (const stack<T>& o) { | |
40 | if ( this == &o ) return *this; | |
41 | clear(); | |
42 | copy(o); | |
[b276be5] | 43 | return *this; |
[122aecd] | 44 | } |
45 | ||
46 | stack& operator= (stack<T>&& o) { | |
47 | if ( this == &o ) return *this; | |
48 | head = o.head; | |
49 | o.head = nullptr; | |
50 | return *this; | |
51 | } | |
52 | ||
[a381b46] | 53 | bool empty() const { return head == nullptr; } |
[309be81] | 54 | |
[c87cd93] | 55 | void push(const T& value) { head = new node{ value, head }; /***/ } |
[309be81] | 56 | |
57 | T pop() { | |
58 | node* n = head; | |
59 | head = n->next; | |
60 | T x = std::move(n->value); | |
61 | delete n; | |
62 | return x; | |
63 | } | |
64 | }; |
Note: See TracBrowser
for help on using the repository browser.