数据结构-栈-数组实现对头的双栈

来源:互联网 发布:网络自学英语 编辑:程序博客网 时间:2024/06/04 01:30

将编号为0和1的两个栈存放于一个数组空间v[m]中,栈底分别处于数组的两端,两端各放一个 栈头指针,
1 当二者相差为1时已经满了
2 当0栈 为-1,1栈为m时已经满了。
有以下操作
出栈,入栈,弹出,判空。初始化

#include <iostream>#include <cstdio>#include <cstdlib>#include <vector>/*二者共享向量空间,迎面增长,当两者间隔为1时就说明满了top表示栈顶指针,而bot是栈尾*/using namespace std;typedef  int ElemType;const int maxn=300;typedef struct{   int top[2],bot[2];//栈顶指针和栈尾指针    vector<ElemType> v;//数组。    int m;//栈最大可容纳数目;}dbstack;dbstack s;bool init(){  s.m=maxn;    s.top[0]=-1;    s.top[1]=s.m;    s.v.assign(maxn,0);    return true;}bool push(int num,int vis){    if(s.top[1]-s.top[0]==1)      {  puts("the stack is full");         return false;      }      if(vis==1)      {   s.top[1]--;           s.v[s.top[1]]=num;      }      else      {   s.top[0]++;          s.v[s.top[0]]=num;      }    return true;}pair<bool,ElemType> pop(int vis){   pair<bool,ElemType> m;    if(vis==0&&s.top[0]==-1)     {  puts("empty");      cout<<s.top[0]<<"!!"<<endl;         m.first=false;         m.second=0;         return m;     }     if(vis==1&&s.top[1]==s.m)     {   puts("empty");         cout<<s.top[1]<<"!!"<<endl;        m.first=false;        m.second=0; return m;     }      m.second=s.v[s.top[vis]];      m.first=true;     return m;}bool top(int vis){ if(vis==1)      s.top[vis]++;      else        s.top[vis]--;    return true;}bool empty1(int vis){   if(vis==1&&s.top[vis]==s.m)    return true;    else if(vis==0&&s.top[vis]==-1)        return true;    return false;}int main(){   init();    push(1,1);    push(2,1);    push(5,0);    push(6,0);    push(7,0);    //cout<<s.top[0]<<" "<<s.top[1]<<endl;    while(!empty1(1))    {        if(pop(1).first)        cout<<pop(1).second<<endl;         top(1);    }    while(!empty1(0))    {    if(pop(0).first)        cout<<pop(0).second<<endl;        top(0);    }    return 0;}
原创粉丝点击