#ifndef _STACK_H_ #define _STACK_H_ using data_t = int; class Stack { public: Stack(); ~Stack(); Stack(Stack const&); Stack& operator=(Stack const&); bool isEmpty() const; void push(data_t const&); data_t pop(); data_t& top(); data_t const& top() const; private: class Element { public: Element(data_t const&, Element* n = nullptr); Element(Element const&) = delete; ~Element(); Element& operator=(Element const&) = delete; static Element* clone(Element const*); Element* next; data_t data; }; Element* mtop; }; #endif #include #include // #include "stack.h" Stack::Stack() : mtop(nullptr) { // intentionally empty } Stack::Stack(Stack const& s) : mtop(Stack::Element::clone(s.mtop)) { // intentionally empty } Stack::~Stack() { delete mtop; } Stack& Stack::operator=(Stack const& rhs) { if ( this != &rhs ) { Stack copy(rhs); std::swap(copy.mtop, mtop); } return *this; } bool Stack::isEmpty() const { return (mtop == nullptr); } void Stack::push(data_t const& d) { mtop = new Element(d, mtop); } data_t Stack::pop() { data_t retval = top(); Element* victim = mtop; mtop = mtop->next; victim->next = nullptr; delete victim; return retval; } data_t& Stack::top() { if (mtop != nullptr) return mtop->data; else throw std::exception(); } data_t const& Stack::top() const { if (mtop != nullptr) return mtop->data; else throw std::exception(); } Stack::Element::Element(data_t const& d, Stack::Element* n) : next(n), data(d) { // intentionally empty } Stack::Element::~Element() { delete next; } Stack::Element* Stack::Element::clone(Element const* s) { if (s != nullptr) return new Element(s->data, clone(s->next)); else return nullptr; } #include int main() { Stack reverse; int n; std::cout << "Mata in heltal: "; while ( std::cin >> n ) reverse.push(n); Stack copy(reverse); Stack inorder; while ( ! copy.isEmpty() ) inorder.push(copy.pop()); std::cout << "Din inmatning var (i rätt ordning): " << std::endl; while ( ! inorder.isEmpty() ) std::cout << inorder.pop() << std::endl; std::cout << "Din inmatning var (i omvänd ordning): " << std::endl; while ( ! reverse.isEmpty() ) std::cout << reverse.pop() << std::endl; return 0; }