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 105 106 107 108 109 110 111 112 113 114 115 116 117 118 |
#ifndef STACK_HPP
#define STACK_HPP 1 #include <cassert> #include <iostream> #include <utility> class Stack { public: Stack() : top(nullptr) { #ifdef DEBUG std::cout << "Stack()" << std::endl; #endif } Stack(const Stack &stack) : top(nullptr) { #ifdef DEBUG std::cout << "Stack(const Stack &)" << std::endl; #endif copy_elements(stack.top); } Stack(Stack &&stack) : Stack() { #ifdef DEBUG std::cout << "Stack(Stack &&)" << std::endl; #endif swap(*this, stack); } ~Stack() { #ifdef DEBUG std::cout << "~Stack()" << std::endl; #endif while (!empty()) { pop(); } } friend void swap(Stack& s1, Stack& s2) { std::swap(s1.top, s2.top); } Stack &operator=(Stack stack) { swap(*this, stack); return *this; } bool empty() const { return !top; } void push(double value) { Element *add = new Element; add->last = top; add->value = value; top = add; } double pop() { assert(!empty()); Element *remove = top; top = remove->last; double value = remove->value; delete remove; return value; } // not asked: just for testing void print(const char *txt = 0) const { if (txt) { std::cout << txt << std::endl; } else { std::cout << "Stack contains:" << std::endl; } print_elements(top); std::cout << std::endl << std::endl; } private: struct Element { Element *last; double value; }; void copy_elements(const Element *element) { if (element) { copy_elements(element->last); push(element->value); } } // not asked: just for testing void print_elements(const Element *element) const { if (element) { print_elements(element->last); std::cout << element->value << " "; } } Element *top; }; #endif // STACK_HPP |