栈的实现

一、相关概念

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;
}

后面我们为大家具体实现两个栈的应用实例,有兴趣的童鞋可以看一下!爱你,么么哒~~

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值