前言
关于共享栈
正文
题目一
共享栈的入栈和出栈操作
共享栈特点
- 栈满top1-top0=0
- 栈空top0=-1,top1=maxsize;
- 左边入栈出栈和右边入栈出栈top移动相反(具体见代码)
代码
#define maxsize 100
typedef struct{
int stack[maxsize];
int top[2];
}stk;
stk s;
//入栈操作
int push(int i,int x){
if(i<0||i>1){
printf("栈号不对");
exit(0);
}
if(s.top[1]-s.top[0]==1){
printf("栈满");
return 0;
}
switch(i){
case 0: s.stack[++s.top[0]]==x;return 1;break;
case 1: s.stack[--s.top[1]]==x;return 1;
}
}
//出栈操作
int pop(int i){
if(i<0||i>1){
printf("栈号不对");
exit(0);
}
switch(i){
case 0:
if(s.top[0]==-1){
printf("栈空");
return -1;
}
else
return s.stack[s.top[0]--];
case 1:
if(s.top[1]==maxsize){
printf("栈空");
return -1;
}
else
return s.stack[s.top[1]++];
}
}
题目二
利用两个栈s1,s2来模拟一个队列
已知栈的四个基本操作,push,pop,StackEmpty,StackOverflow.
总结:
- 对s2的出栈用作出队,若s2为空,则先将s1中的所有元素送入s2
- 对s1的入栈操作用作入队,若s1满,先必须保证s2为空,才能将s1中的元素全部插入s2中
/*入队操作*/
int EnQueue(Stack &s1,Stack &s2,int x){
if(!StackOverflow(s1)){
push(s1,x);
return 1;
}
if(StackOverflow(s1)&&!StackEmpty(s2)){
printf("队列满");
return 0;
}
if(StackOverflow(s1)&&StackEmpty(s2)){
while(!StackEmpty(s1)){
pop(s1,x);
push(s2,x);
}
}
push(s1,x);
return 1;
}
/*出队操作*/
void DeQueue(Stack &s1,Stack &s2,int &x){
if(!StackEmpty(s2)){
pop(s2,x);
}
else if(StackEmpty(s1))
printf("队列为空");
else{
while(!StackEmpty(s1)){
pop(s1,x);
push(s2,x);
}
pop(s2,x);
}
}
/*判断队空*/
int QueueEmpty(Stack s1,Stack s2){
if(StackEmpty(s1)&&StackEmpty(s2))
return 1;
else
return 0;
}