Страница 1 из 1

класс стек на с++

Добавлено: 26 апр 2007, 23:48
Ipse
покажите пожалуйста как в классе реализовываются процедуры:
инициализации, Pop, Push.

Re: класс стек на с++

Добавлено: 27 апр 2007, 15:42
Absurd
Ipse писал(а):покажите пожалуйста как в классе реализовываются процедуры:
инициализации, Pop, Push.
Например так

[php]

#include <memory>
#include <string>
#include <stdexcept>

template<typename ElType>
class Stack {
struct Node {
Node *_next;
ElType _element;
};
Node *_root;
public:
Stack();
~Stack();
void Push(const ElType& el);
ElType Pop();
bool IsEmpty() const;
};

template<typename ElType>
Stack<ElType>::Stack()
:_root(0)
{}

template<typename ElType>
Stack<ElType>::~Stack()
{
while (!IsEmpty()) {
Pop();
}
}

template<typename ElType>
void Stack<ElType>::Push(const ElType& el)
{
std::auto_ptr<Stack<ElType>::Node> pNode(new Stack<ElType>::Node);
pNode->_next = _root;
pNode->_element = el;
_root = pNode.release();
}

template<typename ElType>
ElType Stack<ElType>::Pop()
{
if (!IsEmpty()) {
std::auto_ptr<Stack<ElType>::Node> pNode(_root);
_root=pNode->_next;
return pNode->_element;
} else {
throw std::logic_error("Stack is epmty");
}
}

template<typename ElType>
bool Stack<ElType>::IsEmpty() const {
return _root == 0;
}
[/php]