#include "queue.h"
#include <stdio.h>
#include <stdlib.h>
void initQueue(Queue* Q) {
Q->Head = Q->Tail = (Node*)malloc(sizeof(Node));
if(Q->Head) {
Q->Head->next = NULL;
Q->Head->key = 0;
}
else
exit(0);
}
void push(Queue* Q, ElemType value) {
if(Q->Head) {
Node* pNewNode = createNode(value);
Q->Tail->next = pNewNode;
Q->Tail = pNewNode;
}
else
printf("Initialize queue first.n");
}
void pop(Queue* Q) {
if(Q->Head != Q->Tail) {
Node* pNode = Q->Head->next;
Q->Head->next = pNode->next;
if(pNode == Q->Tail)
Q->Tail = Q->Head;
free(pNode);
}
}
void clear(Queue* Q) {
while(Q->Head != Q->Tail)
pop(Q);
}
void destroy(Queue* Q) {
clear(Q);
free(Q->Head);
}
bool isEmpty(Queue* Q) {
return Q->Head == Q->Tail;
}
int size(Queue* Q) {
if(Q->Head) {
int ret = 0;
Node* pNode = Q->Head;
while (pNode != Q->Tail) {
++ret;
pNode = pNode->next;
}
return ret;
}
else
exit(0);
}
ElemType front(Queue* Q) {
if(Q->Head->next)
return Q->Head->next->key;
else
return 0;
}
ElemType back(Queue* Q) {
return Q->Tail->key;
}
Node* createNode(ElemType value) {
Node* pNewNode = (Node*)malloc(sizeof(Node));
if (pNewNode) {
pNewNode->next = NULL;
pNewNode->key = value;
return pNewNode;
}
else
exit(0);
}
void print(Queue* Q) {
if(Q->Head) {
Node* pNode = Q->Head;
while(pNode != Q->Tail) {
printf("%d ",pNode->next->key);
pNode = pNode->next;
}
}
}
近期评论