用两个栈来实现一个队列,完成队列的Push和Pop操作。 队列中的元素为int类型。
#include<stdio.h>
#include<malloc.h>
typedef struct SqStack{
int *top,*base;
int stacksize;
}SqStack;
int InitStack(SqStack &S){
S.base=(int *)malloc(20*sizeof(int));
if(!S.base) return 0;
S.top=S.base;
S.stacksize=20;
return 1;
}
void PushStack(SqStack &S,int e){
if(S.top-S.base>=S.stacksize){
S.base=(int *)realloc(S.base,(S.stacksize+10)*sizeof(int));
if(!S.base)
return;
S.top=S.base+S.stacksize;
S.stacksize+=10;
}
*S.top++=e;
}
int PopStack(SqStack &S,int &e){
if(S.top==S.base)
return 0;
e=*--S.top;
return 1;
}
int main(){
SqStack S1,S2;
InitStack(S1);
InitStack(S2);
int flag,num;
printf("入队按1,出队按0!\n");
while(~scanf("%d",&flag)){
if(flag==1){
int num;
scanf("%d",&num);
PushStack(S1,num);
printf("入队%d\n",num);
}else if(flag==0){
int out,get=0;
int result;
result=PopStack(S2,out);
if(result==0){
//如果栈2没有数据,则把栈1所有数据进入到栈2
while(PopStack(S1,out)==1){
PushStack(S2,out);
get=1;
}
if(get==1){
PopStack(S2,out);
printf("出队列%d\n",out);
}else
printf("队列暂无数据!\n");
}else if(result==1){
printf("出队列%d\n",out);
}
}
}
}
网友评论