LinkQueue.h
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <malloc.h>
typedef int Elemtype;
typedef struct QueueNode
{
Elemtype data;
struct QueueNode* next;
}QueueNode;
typedef struct LinkQueue
{
QueueNode* front;
QueueNode* tail;
}LinkQueue;
QueueNode* BuyNode(const Elemtype x);
void InitQueue(LinkQueue* Q);
void EnQueue(LinkQueue* Q, const Elemtype x);
void Show_Queue(const LinkQueue* Q);
void DeQueue(LinkQueue* Q);
void GetHead(const LinkQueue* Q, Elemtype* v);
int Length(const LinkQueue* Q);
void ClearQueue(LinkQueue* Q);
void Destroy(LinkQueue* Q);
LinkQueue.cpp
#include "LinkQueue.h"
QueueNode* BuyNode(const Elemtype x)
{
QueueNode* newnode = (QueueNode*)malloc(sizeof(QueueNode));
assert(newnode != NULL);
newnode->data = x;
newnode->next = NULL;
return newnode;
}
void InitQueue(LinkQueue* Q)
{
assert(Q != NULL);
Q->front = Q->tail = BuyNode(0);
}
void EnQueue(LinkQueue* Q, const Elemtype x)
{
assert(Q != NULL);
QueueNode* newnode = BuyNode(x);
Q->tail->next = newnode;
Q->tail = newnode;
}
void Show_Queue(const LinkQueue* Q)
{
assert(Q != NULL);
QueueNode* p = Q->front->next;
printf("Front ");
while (p != NULL)
{
printf("%d-->", p->data);
p = p->next;
}
printf(" Tail\n");
}
void DeQueue(LinkQueue* Q)
{
assert(Q != NULL);
assert(Q->front != Q->tail);
QueueNode* p = Q->front->next;
Q->front->next = p->next;
free(p);
if (Q->front->next == NULL)
{
Q->tail = Q->front;
}
}
void GetHead(const LinkQueue* Q, Elemtype* v)
{
assert(Q != NULL);
assert(Q->front != Q->tail);
QueueNode *p = Q->front->next;
*v = p->data;
}
int Length(const LinkQueue* Q)
{
assert(Q != NULL);
int len = 0;
QueueNode* p = Q->front->next;
while (p != NULL)
{
++len;
p = p->next;
}
return len;
}
void ClearQueue(LinkQueue* Q)
{
assert(Q != NULL);
QueueNode* p = Q->front->next;
while (p != NULL)
{
QueueNode* tmp = p;
p = p->next;
free(tmp);
}
Q->tail = Q->tail;
}
void Destroy(LinkQueue* Q)
{
assert(Q != NULL);
ClearQueue(Q);
free(Q->front);
Q->front = Q->tail = NULL;
}