/* * lstack.cpp * * Created on: 21.03.2014 * Author: trifon */ #ifndef LSTACK_CPP_ #define LSTACK_CPP_ #include template struct StackElement { T data; StackElement* next; }; template class LinkedStack { private: StackElement* top; // самият стек, т.е. указател към // последния включен в стека елемент public: LinkedStack(); // create LinkedStack(LinkedStack const&); // проверка дали стек е празен bool empty() const; // включване на нов елемент bool push(T const&); // изключване на елемент T pop(); // връщане на върха на стека T last() const; // деструктор ~LinkedStack(); // операция за присвояване LinkedStack& operator=(LinkedStack const&); private: // копиране void copy(LinkedStack const&); // изчистване void clean(); }; template LinkedStack::LinkedStack() { top = NULL; } template LinkedStack::LinkedStack(LinkedStack const& ls) { copy(ls); } template void LinkedStack::copy(LinkedStack const& ls) { /* !!! неправилно !!! top = NULL; while(!ls.empty()) push(ls.pop()); */ if (ls.empty()) top = NULL; else { // първа стъпка top = new StackElement; top->data = ls.top->data; // подготовка за втората стъпка StackElement* toCopy = ls.top->next; StackElement* lastCopy = top; while (toCopy != NULL) { // копиране StackElement* newCopy = new StackElement; newCopy->data = toCopy->data; // завързване lastCopy->next = newCopy; // подготовка за следващата стъпка toCopy = toCopy->next; lastCopy = newCopy; } // затваряме веригата lastCopy->next = NULL; } } template bool LinkedStack::empty() const { return top == NULL; } template bool LinkedStack::push(T const& x) { StackElement* el = new StackElement; el->data = x; el->next = top; top = el; return true; } template T LinkedStack::last() const { if (empty()) return T(); return top->data; } template T LinkedStack::pop() { if (empty()) return T(); // top != NULL StackElement* el = top; top = top->next; T x = el->data; delete el; return x; } template LinkedStack::~LinkedStack() { clean(); } template void LinkedStack::clean() { // !!! delete top; // не е достатъчно! while (!empty()) pop(); // за домашно: директна реализация } template LinkedStack& LinkedStack::operator =(LinkedStack const& ls) { if (this != &ls) { clean(); copy(ls); } return *this; } #endif /* STACK_CPP_ */