Queue.h
#pragma once
typedef int DataType;
typedef struct QueueNode
{
struct QueueNode* next;
DataType data;
}QNode;
typedef struct Queue
{
QNode* front;
QNode* back;
}Queue;
void QueueInit(Queue* q);
void QueuePush(Queue* q, DataType data);
void QueuePop(Queue* q);
DataType QueueFront(Queue* q);
DataType QueueBack(Queue* q);
int QueueSize(Queue* q);
int QueueEmpty(Queue* q);
void QueueDestroy(Queue* q);
Queue.c
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "Queue.h"
QNode* NewQueueNode(DataType data)
{
QNode* node = (QNode*)malloc(sizeof(QNode));
if(NULL == node)
{
assert(0);
return NULL;
}
node->data = data;
node->next = NULL;
return node;
}
void QueueInit(Queue* q)
{
assert(q);
q->front = q->back = NewQueueNode(0);
}
void QueuePush(Queue* q, DataType data)
{
assert(q);
q->back->next = NewQueueNode(data);
q->back = q->back->next;
}
void QueuePop(Queue* q)
{
assert(q);
if(QueueEmpty(q))
return;
QNode* delNode = q->front->next;
q->front->next = delNode->next;
if(NULL == delNode->next)
q->back = q->front;
free(delNode);
}
DataType QueueFront(Queue* q)
{
assert(q);
return q->front->next->data;
}
DataType QueueBack(Queue* q)
{
assert(q);
return q->back->data;
}
int QueueSize(Queue* q)
{
assert(q);
int count = 0;
QNode* cur = q->front->next;
while(cur)
{
++count;
cur = cur->next;
}
return count;
}
int QueueEmpty(Queue* q)
{
assert(q);
return NULL == q->front->next;
}
void QueueDestroy(Queue* q)
{
assert(q);
QNode* cur = q->front;
while(cur)
{
q->front = cur->next;
free(cur);
cur = cur->next;
}
q->front = q->back = NULL;
}
test.c
#include <stdio.h>
#include "Queue.h"
int main()
{
Queue q;
QueueInit(&q);
QueuePush(&q,1);
printf("%d\n",QueueSize(&q));
printf("%d\n",QueueFront(&q));
printf("%d\n",QueueBack(&q));
QueuePush(&q,1);
QueuePush(&q,2);
QueuePush(&q,3);
QueuePush(&q,4);
printf("%d\n",QueueSize(&q));
printf("%d\n",QueueFront(&q));
printf("%d\n",QueueBack(&q));
QueuePop(&q);
QueuePop(&q);
printf("%d\n",QueueSize(&q));
printf("%d\n",QueueFront(&q));
printf("%d\n",QueueBack(&q));
if(QueueEmpty(&q))
printf("NULL\n");
else
printf("error\n");
QueuePop(&q);
QueuePop(&q);
QueuePop(&q);
if(QueueEmpty(&q))
printf("NULL\n");
else
printf("error\n");
}