设已知有两个堆栈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思路 这个题代码好写,思路不好想。一开始我把 Stack S1 = (Stack)malloc(sizeof(struct stu)); Stack S2 = (Stack)malloc(sizeof(struct stu)); 设为全局变量,然后怎么改都是编译错误,
text.c:4: error: initializer element is not constant百度了一下发现C语言初始化一个全局变量或static变量时,只能用常量赋值,不能用变量赋值 该题思路,想要实现队列先进先出操作,则两个栈要分工,s2的作为入队,入了两个元素满了,把元素一个一个放进S1(这样S2中元素在S1中倒过来即可先进先出),S1从栈顶开始出队。由题中所给数据大体看栈有2+3个空,S2三个,S1两个(S2中元素会有全部放进S1的过程,故S1.size()>S2.size())但所组合成的队列只能放4个。则S1,S2各可放两个元素。 A 5 D A 6对应 ERROR:Full 1 ERROR:Full 判断出即使S2满了,S1有一个元素,想往里面加数也是不可以的了。 代码
#include <stdio.h> #include <stdlib.h> #define ERROR -1 #define MAXSIZE 100000 struct stu { int data[MAXSIZE]; int top; int max; }; typedef struct stu *Stack; typedef int ElementType; void Push(Stack S, ElementType item ) { if(S->top==S->max-1) return 0; S->data[++S->top]=item; } ElementType Pop(Stack S ) { if(S->top==-1) return -1; int x=S->data[S->top--]; return x; } int IsFull(Stack S) { if(S->top==S->max-1) return 1; return 0; } int IsEmpty(Stack S) { if(S->top==-1) return 1; return 0; } int main() { int N1,N2,flag=1,x; char Z; scanf("%d %d", &N1,&N2); getchar(); int a=N1>N2?N1:N2; int b=N1>N2?N2:N1;/*S1永远大于S2,S1出队,S2入队,S2元素满则放到S1中*/ Stack S1 = (Stack)malloc(sizeof(struct stu)); S1->top=-1; S1->max=a; Stack S2 = (Stack)malloc(sizeof(struct stu)); S2->top=-1; S2->max=b; while (flag) { scanf("%c",&Z); switch(Z) { case 'A': scanf("%d", &x); if(!IsFull(S2)) Push(S2,x);/*S2没满*/ else if(IsFull(S2)&&IsEmpty(S1)) /*S2满了,S1为空*/ { while(!IsEmpty(S2)) /*S2元素放入S1中*/ { int x=Pop(S2); Push(S1,x); } Push(S2,x); } else if(IsFull(S2)&&!IsEmpty(S1))/*S2满了,S1不空*/ printf("ERROR:Full\n"); break; case 'D': if(IsEmpty(S1)&&IsEmpty(S2)) printf("ERROR:Empty\n"); else if(IsEmpty(S1)&&!IsEmpty(S2)) /*把S2元素复制进S1*/ { while(!IsEmpty(S2)) /*S2元素放入S1中*/ { int x=Pop(S2); Push(S1,x); } printf("%d\n", Pop(S1)); } else printf("%d\n", Pop(S1)); break; case 'T': flag=0; break; } } return 0; }