2021-08-17王道 数据结构 p80 第2题

第3章 栈和队列

3.2 队列

综合应用题 第2题

在这里插入图片描述

#include <stdio.h>  
#include <stdlib.h>                        //malloc所在头文件
#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);
	} 
	//PrintQueue(Q);这里打印会改变Q.front的位置  
	while(!QueueEmpty(Q))
	{
	n=DeQueuel(Q);
	Push(S,n);
	}
	while(!StatckEmpty(S))
	{
	n=Pop(S);
	EnQueuel(Q,n);	
	}	
    PrintQueue(Q);
	return 0;
}
```![在这里插入图片描述](https://img-blog.csdnimg.cn/9b0bd1123ec64f6eb3f1dae2f3981f20.png)



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值