栈的实现
一、相关概念
1、STACKS
栈是线性表的一个版本,元素的插入和删除限制在其栈顶进行,相应的插入和删除也被成为入栈和出栈。栈是一个后进先出的表。
二、实现分析
1、栈的基本属性
<1> count–栈的大小;
<2> entry–栈的内容;
2、栈的基本运算
(1)push:先判断这个栈是否已满,否则将元素推进栈中;
(2)pop:判断这个栈是否为空,否则将这个栈中的最后一个元素(栈顶)删除;
(3)top:判断栈是否为空,否则将栈顶的元素送出来;
(4)empty:判断这个栈是否为空;
三、栈的C++实现
栈的实现我们采用的是c++的模板类实现的;
//stack.cpp
const int maxstack = 10;
enum error_code {success, overflow, underflow, fail};
template <class stack_entry>
class stack
{
private:
int count; //the number of element in stack;
stack_entry entry[maxstack]; //the content of the stack;
public:
stack();
bool empty() const;
error_code pop();
error_code push(const stack_entry &item);
error_code top(stack_entry &item) const;
};
//栈的构造函数;
template <class stack_entry>
stack <stack_entry>::stack()
{
count = 0;
}
//判断栈是否为空;
template <class stack_entry>
bool stack<stack_entry>::empty() const
{
if(count > 0)
return false;
else
return true;
}
//将元素推入栈中;
template <class stack_entry>
error_code stack<stack_entry>::push(const stack_entry &item)
{
error_code outcome = success;
if(count >= maxstack) //是否超出栈的最大容量;
outcome = overflow;
else
entry[count++] = item;
return outcome;
}
//删除栈尾元素;
template <class stack_entry>
error_code stack<stack_entry>::pop()
{
error_code outcome = success;
if(count == 0)
outcome = underflow;
else
count --;
return outcome;
}
//读出栈顶元素;
template <class stack_entry>
error_code stack<stack_entry>::top(stack_entry &item)const
{
error_code outcome = success;
if( count == 0)
outcome = fail;
else
item = entry[count-1]; //not count--
return outcome;
}
后面我们为大家具体实现两个栈的应用实例,有兴趣的童鞋可以看一下!爱你,么么哒~~