#ifndef QUEUE_H_INCLUDED
#define QUEUE_H_INCLUDED
typedef int ElemType;
typedef struct SequQueue
{
ElemType *queue;
int front, rear;
int MaxSize;
}Queue;
//队列 front指向的为空,即Q->queue[Q->fornt+1]才为队首元素,以便判别队列是否满与空
/******************************************/
//初始化队列
/******************************************/
void initQueue(Queue* Q, int ms)
{
if (ms <= 10)
{
Q->MaxSize = 10;
}
else
{
Q->MaxSize = ms;
}
Q->queue = calloc(Q->MaxSize, sizeof(ElemType));
if (!Q->queue)
{
printf("分配内存失败!\n");
exit(1);
}
Q->front = Q->rear = 0;
}
/***********************************************************/
//向队列插入元素,若队列已满需重新分配更大内存空间
void enQueue(Queue* Q, ElemType item)
{
if ((Q->rear + 1) % Q->MaxSize == Q->front)//扩大内存
{
int i;
Q->queue = realloc(Q->queue, 2 * sizeof(ElemType) * Q->MaxSize);
if (!Q->queue)
{
printf("申请内存失败!,exit\n");
exit(1);
}
for (i = 0; i <= Q->rear; i++)//把在front前面的元素后移
{
Q->queue[Q->MaxSize + i] = Q->queue[i];
}
Q->rear = Q->rear + Q->MaxSize;//更新rear
Q->MaxSize = Q->MaxSize * 2;//更新MaxSize
}
Q->rear = (Q->rear + 1) % Q->MaxSize;
Q->queue[Q->rear] = item;
}
/*************************************************************/
//从队列中删除元素并返回
ElemType outQueue(Queue* Q)
{
if (Q->front == Q->rear)//检查队列是否为空
{
printf("队列为空,退出!\n");
exit(1);
}
Q->front = (Q->front + 1) % Q->MaxSize;
return Q->queue[Q->front];//删除的元素
}
/*************************************************************/
//读取队首元素,不改变队列状态
ElemType peekQueue(Queue* Q)
{
if (Q->front == Q->rear)
{
printf("队列为空!,退出!");
exit(1);
}
return Q->queue[(Q->front + 1) % Q->MaxSize];
}
/*****************************************************************/
//检查一个队列是否为空,若是则返回1,否则而返回0
int emptyQueue(Queue* Q)
{
return Q->front == Q->rear;
}
/****************************************************************/
//清楚出一个队列为空,并释放动态空间
void clearQueue(Queue* Q)
{
if (Q->queue != NULL)
{
free(Q->queue);
Q->queue = NULL;
Q->front = Q->rear = 0;
Q->MaxSize = 0;
}
}
/****************************************************************/
#endif
#include <stdio.h>
#include <stdlib.h>
#include "Queue.h"
int main ( )
{
int i, x = 12 ;
Queue q;
Queue* Q= & q;
initQueue ( Q, 1 ) ;
enQueue ( Q, 35 ) ;
enQueue ( Q, 2 * x + 3 ) ;
enQueue ( Q, - 16 ) ;
printf ( "%d " , peekQueue ( Q) ) ;
printf ( "%d\n" , outQueue ( Q) ) ;
for ( i = 0 ; i < 30 ; i + = 2 )
{
enQueue ( Q, i) ;
}
while ( ! emptyQueue ( Q) )
{
printf ( "%d " , outQueue ( Q) ) ;
}
printf ( "\n" ) ;
clearQueue ( Q) ;
return 0 ;
}