栈之顺序实现

来源:互联网 发布:四川话在线翻译软件 编辑:程序博客网 时间:2024/05/23 01:49

什么是堆栈:

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

栈堆的特点:

    栈是一种后进先出的数据结构。类似于老师批改作业,当学生上交作业的速度大于老师批改的速度时,需要将提交的作业按提交顺序从下到上依次放在桌面上(进栈),当老师批改作业时,则从上往下批改(出栈)。因此栈又称为后进先出(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;    elsereturn 0;}void SeqStack::SetEmpty(){    top=base=0;    cout<<"栈已清空!"<<endl;}SEType SeqStack::GetTop(){    SEType e;    if(top==base){        cout<<"空栈,没有数据元素"<<endl;e='\0';    }    elsee=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;}


0 0
原创粉丝点击