/* * stack.cpp * * Created on: 11.04.2013 * Author: trifon */ #include using namespace std; #include "stack.h" Stack::Stack() : top(NULL) { } Stack::Stack(Stack const& s) { copyStack(s); } Stack& Stack::operator=(Stack const& s) { if (this != &s) { deleteStack(); copyStack(s); } return *this; } Stack::~Stack() { deleteStack(); } void Stack::copyStack(Stack const& s) { elem* p = s.top; if (p == NULL) // стекът s е празен top = NULL; else { // стекът s има поне 1 елемент // правим копие на първия елемент top = new elem; top->inf = s.top->inf; // насочваме p към втория елемент // (ако има такъв) p = p->link; // q сочи към последния създаден // елемент elem *q = top; while (p != NULL) { q->link = new elem; q = q->link; q->inf = p->inf; p = p->link; } q->link = NULL; } } void Stack::deleteStack() { elem* p; // временна променлива while (top != NULL) { p = top->link; delete top; top = p; } } void Stack::push(int x) { elem *p = new elem; p->inf = x; p->link = top; top = p; } bool Stack::pop(int& x) { if (top == NULL) return false; // стекът не е празен elem* p = top->link; x = top->inf; delete top; top = p; return true; } bool Stack::empty() const { return top == NULL; } int Stack::length() { int x, count = 0; while(pop(x)) count++; // стекът е празен // count съдържа дължината му return count; } void Stack::print() { int x; while(pop(x)) cout << x << ' '; cout << endl; }