#include<iostream>
#include<cstring>
#include<malloc.h>
using namespace std;
const int MaxSize=50;
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int top1,top2;
} DStack;
void Init(DStack *&s)
{
s=(DStack *)malloc(sizeof(DStack));
s->top1=-1;
s->top2=MaxSize;
}
bool EmptyStack(DStack *&s)
{
if(s->top1==-1&&s->top2==MaxSize)
return true;
else
return false;
}
bool Push(DStack *&s,int i,int e)
{
if(i<1||i>2)
{
cout<<"没有这个栈!"<<endl;
return false;
}
if(s->top1==s->top2-1)
{
cout<<"栈已满!"<<endl;
return false;
}
switch(i)
{
case 1:
s->top1++;
s->data[s->top1]=e;
break;
case 2:
s->top2--;
s->data[s->top2]=e;
break;
}
return true;
}
bool Pop(DStack *&s,int i,int &e)
{
if(i<1||i>2)
{
cout<<"没有这个栈!"<<endl;
return false;
}
if(s->top1==-1&&s->top2==MaxSize)
{
cout<<"栈是空的!"<<endl;
return false;
}
switch(i)
{
case 1:
e=s->data[s->top1];
s->top1--;
break;
case 2:
e=s->data[s->top2];
s->top2++;
break;
}
}
bool disp(DStack *&s)
{
if(s->top1==-1)
return false;
for(int i=0; i<=s->top1; i++)
cout<<s->data[i]<<" ";
cout<<" ";
for(int j=MaxSize-1;j>=s->top2;j--)
cout<<s->data[j]<<" ";
cout<<endl;
return true;
}
int main()
{
DStack *s;
int i,e;
ElemType a[MaxSize];
Init(s);
cout<<"请在栈1 中输入5个数字 : ";
for(int i=0; i<5; i++)
{
cin>>e;
Push(s,1,e);
}
cout<<"请在栈2 中输入4个数字 : ";
for(int i=0; i<4; i++)
{
cin>>e;
Push(s,2,e);
}
cout<<"栈s:";
disp(s);
cout<<"请输入你想要进栈的序号以及进栈的数字";
cin>>i>>e;
Push(s,i,e);
cout<<"栈s:";
disp(s);
cout<<"请输入你想要是出栈的序号: ";
cin>>i;
Pop(s,i,e);
cout<<endl<<"栈顶的元素是"<<e<<endl;
cout<<"出栈之后栈s:";
disp(s);
i=EmptyStack(s);
if(i)
cout<<endl<<"此链栈为空!"<<endl;
else cout<<endl<<"此链栈不空!"<<endl;
cout<<endl<<"此栈已经被销毁";
// Destroy(s);
}
额外补充
共享栈