队列:先进先出的线性表
三个要素:
1.存放数据的数组;
2.队列头:指向数据存放的第一个位置
3、队列尾:指向已存放数据的下一个位置
queue.h
#ifndef __QUEUE_H_
#define __QUEUE_H_
typedef struct Queue
{
DataType data[length];
int head;
int tail;
}queue;
queue* CreateQueue();
void DeleteQueue(queue* qu);
int EnQueue(queue* qu, DataType data);
int DeQueue(queue* qu );
bool_t QueueIsEmpty(queue* qu);
bool_t QueueIsFull(queue* qu);
void ShowData_int(queue* qu);
#endif
queue.c
#include"public.h"
#include"queue.h"
queue* CreateQueue()
{
queue *qu = NULL;
qu = (queue*)malloc(sizeof(queue));
if(NULL == qu)
{
return NULL;
}
memset(qu->data, 0x0, sizeof(DataType)*length);
qu->head = 0;
qu->tail = 0;
return qu;
}
void DeleteQueue(queue* qu)
{
if(NULL != qu)
{
free(qu);
qu = NULL;
}
}
int EnQueue(queue* qu, DataType data)
{
if(QueueIsFull(qu))
{
printf("Queue is Full..when enqueue....\n");
return -1;
}
if(qu->tail > qu->head)
{
if(qu->tail + 1 == length)
{
qu->data[qu->tail] = data;
qu->tail = 0;
}
else
{
qu->data[qu->tail++] = data;
}
}
else
{
qu->data[qu->tail++] = data;
}
return 0;
}
int DeQueue(queue* qu )
{
if(QueueIsEmpty(qu))
{
printf("Queue is Empty when dequeue.\n");
return -1;
}
if(qu->head < qu->tail)
{
++qu->head;
}
else
{
if(qu->head + 1 == length)
{
qu->head = 0;
}
else
{
++qu->head;
}
}
return 0;
}
bool_t QueueIsEmpty(queue* qu)
{
if(qu->tail == qu->head)
{
return 1;
}
return 0;
}
bool_t QueueIsFull(queue* qu)
{
if(( (qu->tail + 1) == qu->head ) ||((qu->head == 0) && (qu->tail+1 == length)))
{
return 1;
}
return 0;
}
void ShowData_int(queue* qu)
{
int i = 0;
if(QueueIsEmpty(qu))
{
printf("Queue has NULL.\n");
return;
}
if(qu->head < qu->tail)
{
for(i = qu->head; i < qu->tail; ++i)
{
printf("%d ",qu->data[i]);
}
printf("\n");
}
if(qu->head > qu->tail)
{
for(i = qu->head; i < length;++i)
{
printf("%d ",qu->data[i]);
}
for(i = 0; i< qu->tail; ++i)
{
printf("%d ",qu->data[i]);
}
}
printf("--------------------------------------------------\n\n");
}
test.c
int main()
{
queue* qu = NULL;
int i = 0,j = 0,size = 10;
qu = CreateQueue();
for(i = 0; i < size; ++i)
{
EnQueue(qu, i+1);
}
ShowData_int(qu);
#if 1
size = 90;
for(i = 0; i < size; ++i)
{
EnQueue(qu, i+11);
}
ShowData_int(qu);
size = 70;
for(i = 0; i < size; ++i)
{
DeQueue(qu);
}
ShowData_int(qu);
size = 20;
for(i = 0; i < size; ++i)
{
EnQueue(qu, i+100);
}
ShowData_int(qu);
size = 10;
for(i = 0; i < size; ++i)
{
DeQueue(qu);
}
ShowData_int(qu);
size = 20;
for(i = 0; i < size; ++i)
{
EnQueue(qu, i+200);
}
ShowData_int(qu);
/
size = 50;
for(i = 0; i < size; ++i)
{
DeQueue(qu);
}
ShowData_int(qu);
size = 11;
for(i = 0; i < size; ++i)
{
DeQueue(qu);
}
#endif
return 0;
}