设已知有两个堆栈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 <stdlib.h>
struct stack
{
int *data;
int top;
int maxsize;
};
typedef struct stack * Stack;
void InitStack(Stack &S, int n)
{
S = (Stack)malloc(sizeof(struct stack));
S->data = (int *)malloc( n * sizeof(int));
S->top = -1;
S->maxsize = n;
}
void push(Stack S, int item)
{
S->top++;
S->data[S->top] = item;
}
int pop(Stack S)
{
return S->data[S->top--];
}
int IsFull(Stack S)
{
if (S->top == S->maxsize - 1)
return 1;
else
return 0;
}
int IsEmpty(Stack S)
{
if (S->top == -1)
return 1;
else
return 0;
}
void AddQ(int item, Stack S1, Stack S2)
{
int n;
if (IsFull(S1)==0)
{
push(S1, item);
}
else
{
if (IsEmpty(S2))
{
while (IsEmpty(S1) == 0)
{
n = pop(S1);
push(S2, n);
}
push(S1, item);
}
else
{
printf("ERROR:Full\n");
}
}
}
void DeleteQ(Stack S1, Stack S2)
{
/************** begin **************/
int n;
if(!IsEmpty(S2)){
n=pop(S2);
printf("%d\n",n);
}else if(IsEmpty(S2)&&!IsEmpty(S1)){
while(IsEmpty(S1)==0){
n=pop(S1);
push(S2,n);
}
printf("%d\n",pop(S2));
}else if(IsEmpty(S1)&&IsEmpty(S2)){
printf("ERROR:Empty\n");
}
/************** end **************/
}
int main()
{
int n1, n2;
int num1, num2;
scanf("%d %d", &num1, &num2);
n1=num1<num2?num1:num2;
n2=num1<num2?num2:num1;
Stack S1,S2;
InitStack(S1,n1);
InitStack(S2,n2);
char c;
int d;
scanf("%c", &c);
while (c != 'T')
{
switch (c)
{
case 'A':
scanf("%d", &d);
AddQ(d, S1, S2);
break;
case 'D':
DeleteQ(S1, S2);
break;
}
scanf("%c", &c);
}
return 0;
}