/*
只用两个顺序栈S1,s2(S1、S2的大小分别为Max1、Max2)模拟一个顺序队列时,
不能用到其它的辅助空间。设计用栈的运算实现队列的插入(在可能的条件下,要
保证队列元素要能插入成功)、删除以及队列判空运算。
验证示例如下:
1)S1、S2的大小分别为5;S1栈顶用于模拟队列的队尾,S2栈顶用于模拟队列的队头
2)队列分别有5个元素1、2、3、4、5入队,再来5个元素6、7、8、9、10入队,输出当前队列中的所有元素
3)队列出队1个元素,输出当前队列中的所有元素
4)队列再来一个元素11入队
5)队列出队4个元素,输出当前队列中的所有元素
6)队列出队5个元素,再次出队一个元素
*/
#include <stdio.h>
#include <malloc.h>
#include <string.h>
#include <ctype.h>
#include <math.h>
#define MaxSize 100
typedef int ElementType;
typedef struct {
ElementType data[MaxSize];
int top;
} SqStack;
// 新建栈
SqStack * CreateStack( ) {
SqStack *s;
s = (SqStack *)malloc(sizeof(SqStack));
s->top = -1;
return s;
}
// 判断栈是否为空,是返回1,否返回0
int IsEmpty(SqStack * s) {
if (s->top == - 1)
return 1;
else
return 0;
}
// 判断栈是否为满,是返回1,否返回0
int IsFull(SqStack *s) {
if (s->top == MaxSize - 1)
return 1;
else
return 0;
}
// 压栈操作
void Push( SqStack *s, ElementType x) {
if (s->top == MaxSize - 1)
printf("栈满,不支持压栈操作!");
else
s->data[++(s->top)] = x;
}
// 出栈操作
ElementType Pop( SqStack *s) {
if (s->top == - 1) {
printf("栈空,不支持出栈操作!");
return 0;
} else {
return s->data[(s->top)--];
}
}
// 顺序队列结构体
typedef struct {
SqStack *S1; // 用于入队列
SqStack *S2; // 用于出队列
} SqQueue;
// 创建顺序队列
SqQueue *CreateQueue() {
SqQueue *q = (SqQueue *)malloc(sizeof(SqQueue));
q->S1 = CreateStack();
q->S2 = CreateStack();
return q;
}
// 入队列操作
void EnQueue(SqQueue *q, ElementType x) {
// 将S2中的元素依次弹出并压入S1中
while (!IsEmpty(q->S2)) {
Push(q->S1, Pop(q->S2));
}
// 将新元素压入S1中
Push(q->S1, x);
}
// 出队列操作
ElementType DeQueue(SqQueue *q) {
// 将S1中的元素依次弹出并压入S2中
while (!IsEmpty(q->S1)) {
Push(q->S2, Pop(q->S1));
}
// 返回S2栈顶元素,即队列的头元素
return Pop(q->S2);
}
// 判断队列是否为空
int IsQueueEmpty(SqQueue *q) {
return IsEmpty(q->S1) && IsEmpty(q->S2);
}
// 输出队列元素
void PrintQueue(SqQueue *q) {
SqQueue *temp = CreateQueue();
while (!IsQueueEmpty(q)) {
ElementType element = DeQueue(q);
printf("%d ", element);
EnQueue(temp, element);
}
printf("\n");
// 恢复原队列
while (!IsQueueEmpty(temp)) {
EnQueue(q, DeQueue(temp));
}
}
int main() {
SqQueue *q = CreateQueue();
for (int i = 1; i <= 5; i++) {
EnQueue(q, i);
}
for (int i = 6; i <= 10; i++) {
EnQueue(q, i);
}
printf("原始队列:\n");
PrintQueue(q);
DeQueue(q);
printf("队列出队1个元素后:\n");
PrintQueue(q);
EnQueue(q, 11);
for (int i = 0; i < 4; i++) {
DeQueue(q);
}
printf("队列入队11、出队4个元素后:\n");
PrintQueue(q);
for (int i = 0; i < 6; i++) {
DeQueue(q);
}
return 0;
}