使用两个栈来实现一个队列,完成队列的Enqueue和
Dequeue操作
#pragma warning(disable :4996)
#include <stdio.h>
#include "stack.h"
bool empty_queue(STA s1, STA s2) {
return empty(s1) && empty(s2);
}
void enqueue(STA *s1, STA *s2, Element x) {
push(s1, x);
}
Element dequeue(STA *s1, STA *s2) {
if (empty(*s2)) {
while (!empty(*s1)) {
push(s2, pop(s1));
}
}
return pop(s2);
}
int main() {
STA s1, s2;
makenull(&s1);
makenull(&s2);
int a;//1判断是否为空,2进队,3出队
while (scanf("%d", &a) != EOF) {
switch (a) {
case 1:
printf("%c\n", empty_queue(s1, s2));
break;
case 2:
Element x;
scanf(" %c", &x);
enqueue(&s1, &s2, x);
break;
case 3:
printf("%c\n", dequeue(&s1, &s2));
break;
default:
break;
}
}
return 0;
}
stack.h
#define maxlength 1000
typedef char Element;//定义基础类型
typedef struct STACK {
int top;
Element ele[maxlength];
}STA;
bool empty(STA s) {//判断非空与否
return s.top == -1;
}
void makenull(STA *s) {//置栈为空
s->top = -1;
}
Element top(STA s) {//返回栈顶元素
if (empty(s)) {
return NULL;//栈为空返回为空
}
return s.ele[s.top];
}
Element pop(STA *s) {//弹出栈顶元素并且返回栈顶元素
Element ch = s->ele[s->top];
if (s->top < 0) {
makenull(s);//栈为空则置空并返回空
return NULL;
}
else {
s->top--;//出栈,返回原来栈顶元素
return ch;
}
}
void push(STA *s, Element x) {//压栈
s->ele[++s->top] = x;
}