这篇文章主要介绍了C语言中用利用栈和队列实现队列中的元素逆置的相关资料,对正在学习的小伙伴有一定的参考价值,需要的可以参考一下,希望对你有所帮助
下面举例代码:
提到的Q是一个队列,S是一个空栈,实现将队列中的元素逆置的算法
#include<stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct{
ElemType data[MaxSize];
int front,rear;
}Queue;
typedef struct{
ElemType data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack &S) //初始化栈
{
S.top = -1;
}
bool EmptyStack(SqStack S) //判断栈空
{
if(S.top == -1)
return true;
else
return false;
}
bool OverflowStack(SqStack S) //判断栈是否满
{
if(S.top == MaxSize-1)
return true;
else
return false;
}
bool Push(SqStack &S,ElemType x) //进栈
{
if(OverflowStack(S))
return false;
S.data[++S.top] = x;
return true;
}
bool Pop(SqStack &S,ElemType &x) //出栈
{
if(EmptyStack(S))
return false;
x = S.data[S.top--];
return true;
}
void InitQueue(Queue &Q) //初始化队列
{
Q.front = Q.rear = 0;
}
bool IsEmpty(Queue Q) //判断队列是否为空
{
if(Q.front == Q.rear)
return true;
else
return false;
}
bool IsOverflow(Queue Q) //判断队列是否满
{
if((Q.rear+1)%MaxSize == Q.front)
return true;
else
return false;
}
bool EnQueue(Queue &Q,ElemType x) //进队列
{
if(IsOverflow(Q))
return false;
Q.data[Q.rear] = x;
Q.rear = (Q.rear+1)%MaxSize;
return true;
}
bool DeQueue(Queue &Q,ElemType &x) //出队列
{
if(IsEmpty(Q))
return false;
x = Q.data[Q.front];
Q.front = (Q.front+1)%MaxSize;
return true;
}
bool ReverseQueue(Queue &Q)
{
SqStack S;
ElemType x;
InitStack(S);
while(!IsEmpty(Q)) //当队列不为空时,将队列中的元素依次放入栈中
{
DeQueue(Q,x);
Push(S,x);
}
while(!EmptyStack(S)) //当栈不为空时,再将栈中元素依次放入队列中
{
Pop(S,x);
EnQueue(Q,x);
}
return true;
}
void main()
{
Queue Q;
InitQueue(Q);
EnQueue(Q,1);
EnQueue(Q,2);
EnQueue(Q,3);
ReverseQueue(Q);
printf("%d ",Q.data[Q.front]);
}
(根据主函数中代码)演示:
例如一开始队列中元素为:3 2 1 ->出
1. 将队列中元素依次放到栈中,此时栈:1 2 3 ->出
2. 再将栈中的元素依次放入队列中,此时队列:1 2 3 ->出
到此这篇关于C语言中用栈+队列实现队列中的元素逆置的文章就介绍到这了,更多相关用栈+队列实现队列中的元素逆置内容请搜索编程学习网以前的文章希望大家以后多多支持编程学习网!
沃梦达教程
本文标题为:C语言中用栈+队列实现队列中的元素逆置


猜你喜欢
- 详解C语言中sizeof如何在自定义函数中正常工作 2023-04-09
- ubuntu下C/C++获取剩余内存 2023-09-18
- C语言手把手带你掌握带头双向循环链表 2023-04-03
- C语言qsort()函数的使用方法详解 2023-04-26
- c++ const 成员函数,返回一个 const 指针.但是返回的指针是什么类型的 const? 2022-10-11
- Easyx实现扫雷游戏 2023-02-06
- Qt计时器使用方法详解 2023-05-30
- C++ 数据结构超详细讲解顺序表 2023-03-25
- 我应该为我的项目使用相对包含路径,还是将包含目录放在包含路径上? 2022-10-30
- C语言详解float类型在内存中的存储方式 2023-03-27