您的位置:首页 > 理论基础 > 数据结构算法

数据结构——队列——C++实现队列及其操作

2017-05-22 10:08 639 查看
      队列的存储结构有两种:顺序存储结构和链式存储结构,称为顺序队列和链队列,在顺序队列中,队列满时进行入队操作产生“上溢”,为解决“上溢”问题,可以使用循环队列

C++实现队列的构建和操作:

1:队列的结构体定义

2:置空队列

3:判断是否为空队列

4:进队

5:出队

6:显示整个队中元素

切记亲力亲为,动手实践写代码

Queue.h

#define MAXSIZE 100
typedef int datatype;

typedef struct
{
datatype data[MAXSIZE];
int front,rear;    //表示队列的头尾位置
}Queue;

//置空队列
bool Set_NULL(Queue &Q);

//判断队列是否为空
bool Is_NULL(Queue Q);

//入队
bool En_Queue(Queue &Q,datatype a);

//出队
bool De_Queue(Queue &Q);

//取队列头元素
datatype front_element(Queue Q);

//显示队列元素
bool show(Queue Q);


Queue.cpp

#include "Queue.h"

#include <iostream>
using std::cin;
using std::cout;
using std::endl;

//队列状态说明:
//front = -1 rear = -1 空队列
//front = -1 rear != -1 有元素队列
//front != -1 rear != -1 有元素出队列

//置空队列
bool Set_NULL(Queue &Q)
{
Q.front = -1;
Q.rear = -1;
return true;
}

//判断队列是否为空
bool Is_NULL(Queue Q)
{
if (Q.front == Q.rear)
{
return true;  //队头等于队尾,为空
}
return false;
}

//入队
bool En_Queue(Queue &Q,datatype a)
{
if ((Q.rear - Q.front) >= MAXSIZE-1)
{
cout<<"The queue is full~";
return false;
}
Q.rear += 1;
Q.data[Q.rear] = a;
return true;
}

//出队
bool De_Queue(Queue &Q)
{
if (Is_NULL(Q))
{
cout<<"The queue is empty~";
return false;
}
Q.front += 1;
return true;
}

//取队列头元素
datatype front_element(Queue Q)
{
if (Is_NULL(Q))
{
cout<<"The queue is empty~";
return NULL;
}
return Q.data[Q.rear];
}

//显示队列元素
bool show(Queue Q)
{
if (Is_NULL(Q))
{
cout<<"The queue is empty~";
return false;
}
for (int i = Q.front;i < Q.rear;++i)
{
cout<<Q.data[i+1]<<" ";
}
return true;
}


main.cpp

#include "Queue.h"

#include <iostream>
using namespace std;

int main(int argc,char** argv)
{
Queue Q;
Set_NULL(Q);   //置空

if (Is_NULL(Q))   //判断是否为空
{
cout<<"The queue is empty"<<endl;
}
else
{
cout<<"The queue is not empty"<<endl;
}

En_Queue(Q,2);
En_Queue(Q,5);
En_Queue(Q,9);
En_Queue(Q,3);
En_Queue(Q,2);

show(Q);

De_Queue(Q);
cout<<endl;
cout<<"After the De_queue:";
show(Q);

cout<<endl;
cout<<"The rear element is:"<<front_element(Q);

system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
相关文章推荐