顺序队所尊崇的结点如图
所实现的功能如下:
bool IsFull(Queue *Q);//判满
bool IsEmpty(Queue *Q);//判空
void InitQueue(Queue *Q);//初始化
bool EnQueue(Queue *Q, ElemType x);//入队
bool DeQueue(Queue *Q, ElemType *v);//出队并返回值
bool DeQueue1(Queue *Q);//直接出队
void Show(Queue *Q);//打印
void DestroyQueue(Queue *Q);//摧毁
void ClearQueue(Queue *Q);//删除
具体的代码如下:
头文件:
#pragma once
//循环队列(空闲单元法)
#include<iostream>
using namespace std;
typedef int ElemType;
#define QUEUE_INIT_SIZE 8
typedef struct Queue
{
ElemType *base;
size_t capacity;
int front;
int rear;
}Queue;
bool IsFull(Queue *Q);//判满
bool IsEmpty(Queue *Q);//判空
void InitQueue(Queue *Q);//初始化
bool EnQueue(Queue *Q, ElemType x);//入队
bool DeQueue(Queue *Q, ElemType *v);//出队并返回值
bool DeQueue1(Queue *Q);//直接出队
void Show(Queue *Q);//打印
void DestroyQueue(Queue *Q);//摧毁
void ClearQueue(Queue *Q);//删除
函数定义文件:
#include "SeqQueue.h"
bool IsFull(Queue *Q) //判满
{
return ((Q->rear+1)%(Q->capacity)) == Q->front; //满足时为满
}
bool IsEmpty(Queue *Q) //判空
{
return Q->front == Q->rear; //相等时
}
void InitQueue(Queue *Q) //初始化
{
Q->capacity = QUEUE_INIT_SIZE; //队长
Q->base = (ElemType*)malloc(sizeof(ElemType)*Q->capacity);//队空间的开辟
Q->front = 0; //队头
Q->rear = 0; //队尾
}
bool EnQueue(Queue *Q, ElemType x) //入队
{
if(IsFull(Q)) //判满
{
cout<<"队列已满,不能入队!"<<endl;
return false;
}
Q->base[Q->rear] = x; //入队赋值
Q->rear = (Q->rear+1)%Q->capacity; //重新循环指向
return true;
}
bool DeQueue(Queue *Q, ElemType *v) //出队并返回出队数值
{
if(IsEmpty(Q)) //判空
{
cout<<"队列已空,不能出队!"<<endl;
return false;
}
*v = Q->base[Q->front]; //赋值
Q->front = (Q->front+1) % Q->capacity; //重新循环指向
return true;
}
bool DeQueue1(Queue *Q)//直接出队
{
if(IsEmpty(Q)) //判空
{
cout<<"队列已空,不能出队!"<<endl;
return false;
}
Q->front = (Q->front+1) % Q->capacity;
return true;
}
void Show(Queue *Q) //打印
{
for(int i=Q->front; i!=Q->rear;) //队头到队尾
{
cout<<Q->base[i]<<" ";
i = (i+1)%Q->capacity; //处理i,循环打印
}
cout<<endl;
}
void DestroyQueue(Queue *Q) //摧毁队列
{
free(Q->base);
Q->base = NULL;
Q->capacity = Q->front = Q->rear = 0;
}
void ClearQueue(Queue *Q) //清除队列
{
Q->rear = Q->front;
}测试文件:
#include"SeqQueue.h"
void main()
{
ElemType value;
Queue Q;
InitQueue(&Q);
EnQueue(&Q,1);
EnQueue(&Q,2);
EnQueue(&Q,3);
EnQueue(&Q,4);
EnQueue(&Q,5);
Show(&Q);
DeQueue1(&Q);
DeQueue(&Q,&value);
cout<<value<<"出队!"<<endl;
DeQueue(&Q,&value);
cout<<value<<"出队!"<<endl;
DeQueue(&Q,&value);
cout<<value<<"出队!"<<endl;
DeQueue(&Q,&value);
cout<<value<<"出队!"<<endl;
EnQueue(&Q,6);
EnQueue(&Q,7);
EnQueue(&Q,8);
EnQueue(&Q,9);
Show(&Q);
}对于具体的操作,测试文件写得很清楚,在这里便不用截图说明了。代码有什么问题,希望大家可以指出,谢谢。
原文地址:http://blog.csdn.net/qaz3171210/article/details/45652723