栈之顺序实现

什么是堆栈:

    堆栈是一种特殊的线性结构,和线性表不同的是,其插入和删除受限。

栈堆的特点:

    栈是一种后进先出的数据结构。类似于老师批改作业,当学生上交作业的速度大于老师批改的速度时,需要将提交的作业按提交顺序从下到上依次放在桌面上(进栈),当老师批改作业时,则从上往下批改(出栈)。因此栈又称为后进先出(last in first out)的线性表,简称LIFO线性表。

顺序栈:

    顺序栈是利用一组连续的存储单元依次存放自栈底到栈顶的元素。通常用一维数组来实现。

基本操作:

     进栈时先将数据元素放入栈顶,然后使栈顶指针自加一;出栈时,栈顶指针自减一,然后将该元素取出。

C++源码如下:

/*
**Date:2016-09-21
**Function:Sequence Stack
**Author:DS
*/

#include <iostream>
using namespace std;
const int MAX_SIZE=80;
typedef char SEType;
class SeqStack{
  private:
      SEType elem[MAX_SIZE];
      int base,top;
  public:
      SeqStack(){     //初始化一个空栈
          base=0;
	  top=0;
      }
      ~SeqStack(){    //销毁栈
      }
      int IsEmpty();  //判断栈是否为空
      void SetEmpty();//重置栈为空
      void Push(SEType e);//进栈
      SEType Pop();   //出栈
      SEType GetTop();//取栈顶元素
      int GetLen();   //求栈中元素个数
};
int SeqStack::IsEmpty(){
    if(top==base)
	return 1;
    else
	return 0;
}
void SeqStack::SetEmpty(){
    top=base=0;
    cout<<"栈已清空!"<<endl;
}
SEType SeqStack::GetTop(){
    SEType e;
    if(top==base){
        cout<<"空栈,没有数据元素"<<endl;
	e='\0';
    }
    else
	e=elem[top-1];
    return e;
}
int SeqStack::GetLen(){
  return top-base;
}
void SeqStack::Push(SEType e){  //判断栈是否已满
    if(top==MAX_SIZE)
	cout<<"栈满溢出"<<endl;
    else{
        elem[top]=e;         //元素进栈
	top++;               //修改栈顶指针
    }
}
SEType SeqStack::Pop(){
  SEType e;
  if(top==base){             //判断是否为空栈
      cout<<"栈已空,不能出栈"<<endl;
      e='\0';
  }
  else{
      top--;
      e=elem[top];
  }
  return e;
}
int main(){
    SeqStack S;
    int menu;
    SEType id;
    cout<<"--------------------"<<endl;
    cout<<"-----欢迎测试栈-----"<<endl;
    cout<<"-------1.进栈-------"<<endl;
    cout<<"-------2.出栈-------"<<endl;
    cout<<"------3.求栈长------"<<endl;
    cout<<"-----4.置栈为空-----"<<endl;
    cout<<"----5.求栈顶元素----"<<endl;
    cout<<"-------6.退出-------"<<endl;
    cout<<"--------------------"<<endl;
    while(1){
        cout<<"选择一个编号:";
        cin>>menu;
        if(menu==1){
            cout<<"输入进栈元素:";
            cin>>id;
            S.Push(id);
        }
        else if(menu==2){
          id=S.Pop();
          if(id!='\0')
              cout<<id<<"正在出栈!"<<endl;
        }
        else if(menu==3){
            cout<<"栈长为:"<<S.GetLen()<<endl;
        }
	else if(menu==4){
	    S.SetEmpty();
	}
        else if(menu==5){
            if(S.GetLen()==0)
                cout<<"空栈没有元素!"<<endl;
            else
                cout<<"栈顶元素为:"<<S.GetTop()<<endl;
        }
        else if(menu==6){
            cout<<"再见!"<<endl;
            break;
        }
        else{
            cout<<"输入有误,请重新输入!"<<endl;
        }
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值