第3章 栈和队列
3.2 队列
综合应用题 第2题
![在这里插入图片描述](https://img-blog.csdnimg.cn/3dcf61f88e0140f68b31b2e24b5de89f.png)
#include <stdio.h>
#include <stdlib.h>
#include <iostream>
#define MaxSize 10
using namespace std;
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int front,rear;
}SqQueue;
typedef struct{
ElemType stack[MaxSize];
int top;
}SqStack;
void InitQueue(SqQueue &Q)
{
Q.rear=Q.front=0;
}
void InitStack(SqStack &S)
{
S.top=-1;
}
int EnQueuel(SqQueue &Q,ElemType x)
{
if(Q.rear==MaxSize)
return 0;
Q.data[Q.rear]=x;
Q.rear++;
return 1;
}
int DeQueuel(SqQueue &Q)
{
int x=0;
if(Q.front==Q.rear)
return 0;
x=Q.data[Q.front];
Q.front++;
return x;
}
bool QueueEmpty(SqQueue &Q)
{
if(Q.front==Q.rear)
return true;
else
return false;
}
void PrintQueue(SqQueue &Q)
{
while(Q.front!=Q.rear)
{
cout<<Q.data[Q.front]<<" ";
Q.front++;
}
cout<<endl;
}
int Push(SqStack &S,ElemType x)
{
if(S.top==MaxSize-1)
{
cout<<"栈满"<<endl;
exit(0);
}
S.stack[++S.top]=x;
return 1;
}
int Pop(SqStack &S)
{
int x=0;
if(S.top==-1)
{
cout<<"栈空"<<endl;
return 0;
}
x=S.stack[S.top--];
return x;
}
bool StatckEmpty(SqStack &S)
{
if(S.top==-1)
return true;
else
return false;
}
int main() {
SqQueue Q;
SqStack S;
InitQueue(Q);
InitStack(S);
int n=5,i=1;
for(;i<=n;i++)
{
EnQueuel(Q,i);
}
while(!QueueEmpty(Q))
{
n=DeQueuel(Q);
Push(S,n);
}
while(!StatckEmpty(S))
{
n=Pop(S);
EnQueuel(Q,n);
}
PrintQueue(Q);
return 0;
}
```![在这里插入图片描述](https: