#include <stdio.h>
#include <stdlib.h>
#define QUEUE_CAPACITY 3
typedef struct tag_queue
{
int *pQueue;
int head;
int tail;
int length;
}LineQueue;
int InitQueue(LineQueue **myQueue);
void DestroyQueue(LineQueue *myQueue);
void ClearQueue(LineQueue *myQueue);
int QueueEmpty(LineQueue *myQueue);
int QueueFull(LineQueue *myQueue);
int QueueLength(LineQueue *myQueue);
int EnQueue(LineQueue *myQueue, int element);
int DeQueue(LineQueue *myQueue, int *element);
void QueueTraverse(LineQueue *myQueue);
int InitQueue(LineQueue **myQueue)
{
(*myQueue) = (LineQueue *)malloc(sizeof(LineQueue));
if(myQueue == NULL)
{
return 0;
}
(*myQueue)->pQueue = (int *)malloc(sizeof(int) * QUEUE_CAPACITY);
if((*myQueue)->pQueue == NULL)
{
return 0;
}
(*myQueue)->head = 0;
(*myQueue)->tail = 0;
(*myQueue)->length = 0;
return 1;
}
void DestroyQueue(LineQueue *myQueue)
{
free(myQueue->pQueue);
myQueue->pQueue = NULL;
free(myQueue);
myQueue = NULL;
}
void ClearQueue(LineQueue *myQueue)
{
myQueue->length = 0;
myQueue->tail = 0;
}
int QueueEmpty(LineQueue *myQueue)
{
if(myQueue->length == 0)
{
return 1;
}
return 0;
}
int QueueFull(LineQueue *myQueue)
{
if(myQueue->length >= QUEUE_CAPACITY)
{
return 1;
}
return 0;
}
int QueueLength(LineQueue *myQueue)
{
return myQueue->length;
}
int EnQueue(LineQueue *myQueue, int element)
{
if(QueueFull(myQueue))
{
return 0;
}
myQueue->pQueue[myQueue->tail] = element;
myQueue->tail++;
myQueue->length++;
return 1;
}
int DeQueue(LineQueue *myQueue, int *element)
{
int i = 0;
if(QueueEmpty(myQueue))
{
return 0;
}
*element = myQueue->pQueue[myQueue->head];
for(i = 1; i < myQueue->length; i++)
{
myQueue->pQueue[i-1] = myQueue->pQueue[i];
}
myQueue->length--;
myQueue->tail--;
return 1;
}
void QueueTraverse(LineQueue *myQueue, int flag)
{
int i = 0;
if(flag == 0)
{
for(i = 0; i < myQueue->length; i++)
{
printf("%d ", myQueue->pQueue[i]);
}
}
if(flag == 1)
{
for(i = myQueue->length - 1; i >= 0; i--)
{
printf("%d ", myQueue->pQueue[i]);
}
}
}
int main(void)
{
int elem = 0;
LineQueue *queue = NULL;
InitQueue(&queue);
if(QueueEmpty(queue))
{
printf("当前队列为空\n");
}
EnQueue(queue, 2);
EnQueue(queue, 4);
EnQueue(queue, 5);
if(QueueFull(queue))
{
printf("当前队列为满\n");
}
QueueTraverse(queue, 0);
printf("\n-----------------------\n");
printf("queueLength = %d\n", QueueLength(queue));
ClearQueue(queue);
if(QueueEmpty(queue))
{
printf("当前队列为空\n");
}
DestroyQueue(queue);
system("pause");
return 0;
}
|