#ifndef CHAIN_STACKH #define CHAIN_STACKH #include #include "stack.h" #include "node.h" template class chainStack : public Stack{ private: Node* first; Node* last; int stackTop; public: chainStack() = delete; chainStack(Node* f = nullptr); chainStack(const chainStack& x); virtual bool empty() const; virtual int size() const; virtual T& top(); virtual void pop(); virtual void push(const T& theElement); virtual void show() const; ~chainStack(); }; template inline chainStack::chainStack(Node* f) :first(f), stackTop(0), last(nullptr) { Node* p = first; while (p) { ++stackTop; p = p->next; } } template inline chainStack::chainStack(const chainStack& x) { Node* run = x.first; Node* tnext = nullptr; Node* tprev = nullptr; while (run) { Node* tmp = new Node(run->element, tprev, tnext); if(tprev) tprev->next = tmp; if (!tprev) first = tmp; tprev = tmp; run = run->next; } last = tprev; } template inline bool chainStack::empty() const { return (stackTop == 0); } template inline int chainStack::size() const { return stackTop; } template inline T& chainStack::top() { return last->element; } template inline void chainStack::pop() { if (stackTop == 0) throw std::invalid_argument("Pop Error: No Element in Stack"); if (last) { Node* tmp = last; last = last->prev; if (last) { last->next = nullptr; } else { first = nullptr; } delete tmp; stackTop--; } } template inline void chainStack::push(const T& theElement) { Node* tmp = new Node(theElement, last, nullptr); if (last) last->next = tmp; else first = tmp; last = tmp; stackTop++; } template inline void chainStack::show() const { Node* p = first; while (p) { std::cout << p->element << " "; p = p->next; } std::cout << std::endl; } template inline chainStack::~chainStack() { Node* p = first; Node* that; while (p) { that = p; p = that->next; delete that; } first = nullptr; last = nullptr; stackTop = 0; } #endif // !CHAIN_STACKH