如有不对,不吝赐教
直接进入正题:
设已知有两个堆栈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()。
输入格式:
输入首先给出两个正整数N1和N2,表示堆栈S1和S2的最大容量。随后给出一系列的队列操作:A item表示将item入列(这里假设item为整型数字);D表示出队操作;T表示输入结束。
输出格式:
对输入中的每个D操作,输出相应出队的数字,或者错误信息ERROR:Empty。如果入队操作无法执行,也需要输出ERROR:Full。每个输出占1行。
输入样例:
3 2
A 1 A 2 A 3 A 4 A 5 D A 6 D A 7 D A 8 D D D D T
输出样例:
ERROR:Full
1
ERROR:Full
2
3
4
7
8
ERROR:Empty
其实我不理解为什么非得要用两个栈去模拟队列估计这样可以加深对栈的理解吧
其实这道题目的关键在于如何搭配这些操作:
下面用small表示容量较小的栈,large表示较大的栈
AddQ:
1.small没满,large为空,直接加入small中
2.small满了,large为空,把small的元素全倒入large中,此时large中的元素按照输入顺序
3.small满了,large不为空,报错
DeleteQ:
1.large中有元素,直接Pop
2.large中没有元素大数据堆栈,small中有元素,把small中的元素倒入large中,在Pop
3.small与large中都没有元素,报错
如果看文字困难的话,可以照着文字画下图加深理解
下面给出代码:
#include<stdio.h>
#include<malloc.h>
#define BUG 99999
struct Stack{
int volume;
int tail;
int *data;
};
struct Stack *large,*small;
void AddQ(int item);
int DeleteQ(void);
int IsFull(char s);
int IsEmpty(char s);
void Push(char s,int item);
int Pop(char s);
int main(void)
{
int N1,N2;
int item;
char ch;
fscanf(stdin,"%d %d",&N1,&N2);
fscanf(stdin,"%c",&ch);
large=(struct Stack *)malloc(sizeof(struct Stack));
small=(struct Stack *)malloc(sizeof(struct Stack));
large->volume=N1>N2?N1:N2;
large->data=(int *)malloc(large->volume*sizeof(int));
large->tail=-1;
small->volume=N1<N2?N1:N2;
small->data=(int *)malloc(small->volume*sizeof(int));
small->tail=-1;
while(fscanf(stdin,"%c",&ch),'T'!=ch){
if('A'==ch){
fscanf(stdin,"%d",&item);
AddQ(item);
}
else{
item=DeleteQ();
if(BUG!=item)
printf("%d\n",item);
}
fscanf(stdin,"%c",&ch);
}
return 0;
}
int IsFull(char s)
{
if('l'==s)
return large->tail==large->volume-1;
else
return small->tail==small->volume-1;
}
int IsEmpty(char s)
{
if('l'==s)
return large->tail==-1;
else
return small->tail==-1;
}
void Push(char s,int item)
{
struct Stack *stack;

if('l'==s)
stack=large;
else
stack=small;
stack->data[++(stack->tail)]=item;
return ;
}
int Pop(char s)
{
struct Stack *stack;
if('l'==s)
stack=large;
else
stack=small;
return stack->data[stack->tail--];
}
void AddQ(int item)
{
if(!IsFull('s'))
Push('s',item);
else if(IsEmpty('l')){
while(!IsEmpty('s'))
Push('l',Pop('s'));
Push('s',item);
}
else
printf("ERROR:Full\n");
return ;
}
int DeleteQ(void)
{
int result=BUG;
if(!IsEmpty('l'))
result=Pop('l');
else if(!IsEmpty('s')){
while(!IsEmpty('s'))
Push('l',Pop('s'));
result=Pop('l');
}
else
printf("ERROR:Empty\n");
return result;
}
结果:

(编辑:海南站长网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!
|