利用两个栈s1,s2模拟一个队列时,如何用栈的运算来实现该队列的运算?写出模拟队列插入和删除的函数。一个栈s1用于插入元素,另一个栈s2用于删除元素。
前置知识点(栈定义,及出栈入栈函数)
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdbool.h>
#define MaxSize 5
typedef struct {int data[MaxSize];//栈中元素int top;//栈顶指针
}SqStack;void InitStack(SqStack* S) {//栈初始化(*S).top = -1;
}bool StackEmpty(SqStack* S) {//判空if ((*S).top == -1) {//栈中无元素return true;}else {return false;}
}bool Pop(SqStack* S, int* x) {//出栈if (S->top == -1) {//栈中无元素return false;}*x = S->data[S->top];S->top--;return true;
}bool Push(SqStack* S, int x) {//入栈if (S->top == MaxSize - 1) {return false;}S->top++;S->data[S->top] = x;return true;
}
模拟入队:
//模拟入队
int EnQueue(SqStack* s1, SqStack* s2,int x) {int tmp = 0;//用于后面出栈带出出栈元素if (s1->top==MaxSize-1) {//s1满了if (!StackEmpty(s2)) {//s2只有满和空两种状态,这里不空就是满了printf("队列已满,入队失败!");return 0;}else {//s2为空,把s1的元素全部赋给它,注意,是全部!while (!StackEmpty(s1)) {Pop(s1, &tmp);Push(s2, tmp);}}Push(s1, x);}else {//s1没满,直接压进去就行了Push(s1, x);}return 1;
}
模拟出队
//模拟出队
int DeQueue(SqStack* s1, SqStack* s2, int* x) {int tmp = 0;//用于后面出栈带出出栈元素if (!StackEmpty(s2)) {//s2不空,直接从s2出Pop(s2, x);return 1;}else {//s2是空的if (StackEmpty(s1)) {//s1也是空的printf("队列已空,出队失败");}else {//s1不空//把s1的元素全部移动到s2, 注意,是全部!while (!StackEmpty(s1)) {Pop(s1, &tmp);Push(s2, tmp);}}}Pop(s2, x);return 1;
}
模拟队列打印函数
void Qprint(SqStack s1,SqStack s2) {//两个栈实现的模拟队列打印int tmp = 0;while (!StackEmpty(&s2)) {//s2不空Pop(&s2, &tmp);printf("%d ", tmp);}while (!StackEmpty(&s1)) {//s1不空,把s1的元素全部移动到s2Pop(&s1, &tmp);Push(&s2, tmp);}while (!StackEmpty(&s2)) {//s2又有元素了,重复上面的操作Pop(&s2, &tmp);printf("%d ", tmp);}
}
入队用例测试
int main() {//入队测试SqStack s1;//每个栈5个大小,最终的队列最大size为10SqStack s2;InitStack(&s1);InitStack(&s2);int x = 0;printf("请输入要入队的元素:");while (scanf("%d", &x) != EOF) {int tmp=EnQueue(&s1, &s2, x);//看看当前是否成功入队if (tmp == 1) {printf("当前队列中元素为:");Qprint(s1, s2);printf("\n");}}printf("\n");return 0;
}
出队用例测试
int main() {//入队测试SqStack s1;//每个栈5个大小,最终的队列最大size为10SqStack s2;InitStack(&s1);InitStack(&s2);//先入队五个EnQueue(&s1, &s2, 1);EnQueue(&s1, &s2, 2);EnQueue(&s1, &s2, 3);EnQueue(&s1, &s2, 4);EnQueue(&s1, &s2, 5);printf("\n");//出队测试int x = 5;int tmp = 0;while (x) {DeQueue(&s1, &s2, &tmp);printf("已移除队首元素%d ", tmp);printf("当前队列元素为:");Qprint(s1, s2);printf("\n");x--;}return 0;
}