/* * lstack.cpp * * Created on: 24.10.2012 * Author: trifon */ #include "stack.h" using namespace std; template class LStack : public Stack { public: template struct elem { U inf; elem* link; }; private: elem* top; void delstack() { T tmp; while (pop(tmp)); } // O(n) void copystack(LStack const& stack) { if (stack.top == NULL) { top = NULL; return; } // stack.top != NULL elem* p = stack.top; top = new elem; top->inf = p->inf; elem* r = top; elem* q; p = p->link; // p - елементът, който ще копираме // q - елементът, който създаваме // r - последно създаденият елемент while (p) { q = new elem; q->inf = p->inf; r->link = q; p = p->link; r = q; } r->link = NULL; } public: LStack() : top(NULL) {} // O(n) LStack(LStack const& stack) { copystack(stack); } // O(n) LStack& operator=(LStack const& stack) { if (this != &stack) { delstack(); copystack(stack); } return *this; } ~LStack() { delstack(); } bool empty() const { return top == NULL; } bool push(T const& x) { elem* p = new elem; if (p == NULL) return false; p->inf = x; p->link = top; top = p; return true; } bool peek(T& x) const { if (empty()) return false; x = top->inf; return true; } bool pop(T& x) { if (!peek(x)) return false; elem* p = top; top = top->link; delete p; return true; } // O(n) void print() const { elem* p = top; while (p) { cout << p->inf << endl; p = p->link; } } };