数据结构-顺序栈的实现

数据结构-顺序栈

栈是一种受限的线性表,其受限型体现在所有插入与删除都在表的同一端进行,这一端也称为栈顶。主要以下几个操作

  • 向栈内压入一个元素push()
  • 从栈顶弹出一个元素(删除)pop()
  • 判断栈是否为空empty()
  • 返回栈顶但不删除成员top()

本例中栈定义通过C++模板类实现,实现思路及代码来自王治和教授数据结构课堂的总结

栈的c++实现

const int maxStack=8;
typedef int stack_entry;
enum error_code{
    success,overflow,underflow,fail
};
template <class stack_entry>
class stack{
    private:
        int count;
        stack_entry entry[maxStack];
    public:
        stack();
        error_code push(const stack_entry &item);
        error_code pop();
        bool empty() const;
        error_code top(stack_entry &item);
};
template <class stack_entry>
stack<stack_entry>::stack()
{
    count = 0;
}
//入栈
template <class stack_entry>
error_code stack<stack_entry>::push(const stack_entry &item){
    //const修饰函数参数时,该参数在函数内不可改变
    //item=1;编译出错 
    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>
bool stack<stack_entry>::empty() const{
    bool outcome=true;
    if(count>0)
        outcome=false;
    return outcome;
}
//读出栈顶元素 
template <class stack_entry>
error_code stack<stack_entry>::top(stack_entry &item){
    error_code outcome=success;
    if(count==0)
        outcome=fail;
    else{
        item=entry[count-1];
        cout<<item<<endl;   
    }
    return  outcome;
}

编写测试代码

#include "stack.cpp"
#include <iostream>
using namespace std;
int main(){
    stack<int> intStack;
    for(int i=0;i<8;i++){
        intStack.push(i);
    }
    if(intStack.empty())
        cout<<"该栈为空!"<<endl;
    else{
        cout<<"该栈不为空!"<<endl;
    }
    intStack.pop();
    int topItem;
    intStack.top(topItem);
    cout<<topItem<<endl;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值