基于数组的队列实现(C语言) - ahljjun的专栏 - 博客频道 - CSDN.NET
/*****************************************
接口文件QUEUE.h
****************************************/
#ifndef _QUEUE_H
#define _QUEUE_H#ifndef BOOL
#define BOOL int
#endiftypedef int Item;
struct _Queue;
typedef struct _Queue Queue;typedef Queue* hQueue;//handle to Queue
hQueue Queue_Init(int nMax);
void Queue_Destroy(hQueue q);
void Queue_Put(hQueue q, Item elem);
Item Queue_Get(hQueue q);
int Queue_Size(hQueue q);
BOOL Queue_IsEmpty(hQueue q);
BOOL Queue_IsFull(hQueue q);
#endif/*******************************
实现文件QUEUE.c
*******************************/
#include<stdio.h>
#include<stdlib.h>
#include"QUEUE.h"void Error(char* msg)
{
printf("Error:%s",msg);
}
//机遇数组的队列实现
struct _Queue
{
Item* elem;
int head,tail;
int N;
};hQueue Queue_Init(int nMax)
{
hQueue que=malloc(sizeof(*que));
que->elem=malloc((nMax+1)*sizeof(*que->elem));
que->head=que->tail=0;
que->N=nMax+1;
return que;
}
void Queue_Destroy(hQueue que)
{
if(que->elem)
free(que->elem);
que->elem=NULL;
free(que);
que=NULL;}
void Queue_Put(hQueue que, Item elem)
{
if(Queue_IsFull(que))
{
Error("The Queue Is Full!/n");
exit(-1);
}
que->elem[que->tail]=elem;
que->tail=(que->tail+1)%(que->N);
}Item Queue_Get(hQueue que)
{
Item elem;
if(Queue_IsEmpty(que))
{
Error("The Queue Is Empty!/n");
exit(-1);
}
elem=que->elem[que->head];
que->head=(que->head+1)%(que->N);
return elem;
}int Queue_Size(hQueue que)
{
return (que->tail-que->head+que->N)%(que->N);
}BOOL Queue_IsEmpty(hQueue que)
{
return (que->head==que->tail);
}
BOOL Queue_IsFull(hQueue que)
{
return (que->head==(que->tail+1)%(que->N));
}/******************************
测试文件main.c
********************************/
#include<stdio.h>
#include<stdlib.h>
#include"QUEUE.h"
int main()
{
hQueue q=Queue_Init(7);
int t=7;
while(t)
Queue_Put(q,t--);printf("Queue:%d/n",Queue_Get(q));
printf("Queue:%d/n",Queue_Get(q));
printf("Queue:%d/n",Queue_Get(q));printf("Queu Size= %d/n",Queue_Size(q));
printf("******************************************/n");
t=30;
Queue_Put(q,t--);
Queue_Put(q,t--);printf("Queu Size= %d/n",Queue_Size(q));
while(!Queue_IsEmpty(q))
printf("Queue:%d/n",Queue_Get(q));
Queue_Destroy(q);
return 0;
}