题目
设已知有两个堆栈S1和S2,请用这两个堆栈模拟出一个队列Q。
所谓用堆栈模拟队列,实际上就是通过调用堆栈的下列操作函数:
int IsFull(Stack S):判断堆栈S是否已满,返回1或0;
int IsEmpty (Stack S ):判断堆栈S是否为空,返回1或0;
void Push(Stack S, ElementType item ):将元素item压入堆栈S;
ElementType Pop(Stack S ):删除并返回S的栈顶元素。
实现队列的操作,即入队void AddQ(ElementType item)和出队ElementType DeleteQ()
代码
#include<stdio.h>
#include<stdlib.h>
typedef struct stack{
int *data;
int top;
int capacity;
}st,*St;
bool IsFull(St a);
bool IsEmpty(St a);
void push(St a,int k);
int pop(St a);
void add(St small,St big,int k);
void deqeu(St small,St big);
void main(){
int N1,N2,i;
char a,b,c;
St small,big;
small=(St)malloc(sizeof(st));
big=(St)malloc(sizeof(st));
scanf("%d",&N1);
scanf("%d",&N2);
if(N1<=N2){
small->capacity=N1;
big->capacity=N2;
small->data=(int *)malloc(sizeof(int) * N1);
big->data=(int *)malloc(sizeof(int) * N2);
small->top=-1;
big->top=-1;
}
else{
small->capacity=N2;
big->capacity=N1;
small->data=(int *)malloc(sizeof(int) * N2);
big->data=(int *)malloc(sizeof(int) * N1);
small->top=-1;
big->top=-1;
}
while(1){
//a=getchar();
//a=getchar();
scanf("%c",&a);
a=getchar();
if(a=='T')
break;
else if(a=='A'){
scanf("%d",&i);
add(small,big,i);
}else if(a=='D'){
deqeu(small,big);
}
}
system("pause");
}
void add(St small,St big,int k){
if(!IsFull(small) )
push(small,k);
else if( IsEmpty(big) ){
while(!IsEmpty(small))
push(big,pop(small));
push(small,k);
}else
printf("ERRO FULL\n");
}
void deqeu(St small,St big){
if(!IsEmpty(big))
printf("%d\n", pop(big) );
else if(!IsEmpty(small)){
while(!IsEmpty(small))
push(big,pop(small));
printf("%d\n",pop(big));
}
else
printf("ERRO EMPTY\n");
}
bool IsFull(St a){
if(a->top == (a->capacity-1))
return true;
else
return false;
}
bool IsEmpty(St a){
if(a->top==-1)
return true;
else
return false;
}
void push(St a,int k){
int index;
a->top=a->top+1;
a->data[a->top]=k;
}
int pop(St a){
int k;
k=a->data[a->top--];
return k;
}
思路
整体思路就是利用两个栈中元素相互转移的方法来实现队列操作,通过此题不难发现两个栈其实只用了相同容量位置,big栈的多余位置是无用的,具体如果出现big栈是samll栈多倍的情况 还要具体分析,此时应该就需加入栈大小以及栈内已存元素的判断。