source:
doc/papers/general/evaluation/cpp-stack.hpp
@
49eb6a2
Last change on this file since 49eb6a2 was 860f19f, checked in by , 7 years ago | |
---|---|
|
|
File size: 1004 bytes |
Rev | Line | |
---|---|---|
[604e76d] | 1 | #pragma once |
2 | #include <utility> | |
3 | ||
[81e8ab0] | 4 | template<typename T> struct stack { |
[604e76d] | 5 | struct node { |
6 | T value; | |
[81e8ab0] | 7 | node * next; |
8 | node( const T & v, node * n = nullptr ) : value( v ), next( n ) {} | |
[604e76d] | 9 | }; |
[81e8ab0] | 10 | node * head; |
11 | ||
12 | stack() : head( nullptr ) {} | |
[3d8f2f8] | 13 | stack( const stack<T> & o ) { copy( o ); } |
[604e76d] | 14 | |
15 | void clear() { | |
[81e8ab0] | 16 | for ( node * next = head; next; ) { |
17 | node * crnt = next; | |
[604e76d] | 18 | next = crnt->next; |
19 | delete crnt; | |
20 | } | |
21 | head = nullptr; | |
22 | } | |
23 | ||
[8b001bd] | 24 | void copy( const stack<T> & o ) { |
25 | node ** crnt = &head; | |
26 | for ( node * next = o.head; next; next = next->next ) { | |
27 | *crnt = new node{ next->value }; /***/ | |
28 | crnt = &(*crnt)->next; | |
29 | } | |
30 | *crnt = nullptr; | |
31 | } | |
32 | ||
[604e76d] | 33 | ~stack() { clear(); } |
34 | ||
[81e8ab0] | 35 | stack & operator= ( const stack<T> & o ) { |
[604e76d] | 36 | if ( this == &o ) return *this; |
37 | clear(); | |
[81e8ab0] | 38 | copy( o ); |
[604e76d] | 39 | return *this; |
40 | } | |
41 | ||
42 | bool empty() const { return head == nullptr; } | |
43 | ||
[81e8ab0] | 44 | void push( const T & value ) { head = new node{ value, head }; /***/ } |
[604e76d] | 45 | |
46 | T pop() { | |
[81e8ab0] | 47 | node * n = head; |
[604e76d] | 48 | head = n->next; |
[81e8ab0] | 49 | T v = std::move( n->value ); |
[604e76d] | 50 | delete n; |
[81e8ab0] | 51 | return v; |
[604e76d] | 52 | } |
53 | }; |
Note: See TracBrowser
for help on using the repository browser.