数据结构---队列顺序存储实现(数组)

/*
	队列的实现方式-----------------顺序存储方式-----数组 
	数组+头位置+尾位置 
*/
#include "stdio.h"
#include "stdlib.h"

//#define MaxSize 20
#define ERROR  (1 << 16)  //错误码  有可能跟数据会有冲突 

typedef enum{false,true}bool;
typedef int ElementType;
typedef struct _Queue{
	ElementType *Data;
	int rear;	//后指向 先插后移动 
	int front;	//前指向 先弹出 后移动 
	int MaxSize;
	int count;//记录资源个数  判断队列 空/满 
}Queue;//在队列的头部删除 尾部插入 

//创建一个队列
Queue * CreateQueue(int MaxSize)
{
	Queue * queue = (Queue *)malloc(sizeof(struct _Queue));//申请一块队列变量
	queue->Data = 	(ElementType *)malloc(sizeof(ElementType)*MaxSize);//申请一块数组空间 
	queue->front = 0;
	queue->rear = 0;//头尾 都为0 
	queue->MaxSize = MaxSize;
	queue->count =0;
	
	return queue;
} 

//判断队列是否已满
bool IsFullQ(Queue *Q)
{
	if(Q->count == Q->MaxSize)//说明资源已满
		return true;
	return false;	
} 

//队列插入  循环队列的实现 
void Enqueue(Queue *Q,ElementType item) 
{
	if(IsFullQ(Q))//如果已满
		return ; 
	//没有满的时候 将元素插入队列 先插入当前位置 之后 在移动rear 
	Q->count++;
	if( Q->rear == Q->MaxSize-1 ){
		Q->Data[Q->rear] = item;
		Q->rear = 0;
	}
	else
		Q->Data[Q->rear++] = item;
}

//判断队列是否为空
bool IsEmptyQ(Queue *Q)
{
	if(Q->count == 0)//表示为空 
		return true;
	return false;
} 

//出队列
ElementType Dequeue(Queue *Q)
{
	ElementType temp;
	if( IsEmptyQ(Q) )//若为空  返回错误码 
		return ERROR; 
	//不为空
	Q->count--;
	if(Q->front == Q->MaxSize-1) {
		temp = Q->Data[Q->front];
		Q->front = 0;
		return temp;
	}
	else
		return Q->Data[Q->front++];
	
} 

int main(int argc ,const char *argv[])
{
	Queue * queue = CreateQueue(6);
	int i;
	for(i = 0;i<7;i++)
	{
		Enqueue(queue,i+1);
	}
	for(i = 0;i<8;i++)
		printf("queue[%d] = %d\n",i,Dequeue(queue));
	return 0;
}
posted @ 2017-08-05 20:06  灰色的石头  阅读(337)  评论(0编辑  收藏  举报