//Author:Guo R.H
//Date:06.12.25
// USTC
#include
#include
typedef struct QNode
{
int data;
struct QNode *next;
}QNode, *QPtr;
typedef struct QLink
{
QPtr front;
QPtr rear;
}QLink;
void Error(char *s)
{
printf("%s\n",s);
}
void InitQueue(QLink *Q)
{
Q->front = ( QPtr )malloc(sizeof(QNode));
if(!Q->front)
{
Error("InitQueue memory error!");
exit(0);
}
Q->rear = Q->front;
Q->front->next = NULL;
}
void ClearQueue(QLink *Q)
{
QPtr q, p = Q->front->next;
Q->rear = Q->front;
Q->front->next = NULL;
while(p)
{
q = p;
p = p->next;
free(q);
}
}
void DestroyQueue(QLink *Q)
{
while(Q->front)
{
Q->rear = Q->front->next;
free(Q->front);
Q->front = Q->rear;
}
}
void EnQueue(QLink *Q, int i)
{
QPtr p;
p = ( QPtr )malloc(sizeof(QNode));
if(!p)
{
Error("EnQueue memory error!");
exit(0);
}
p->data = i;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
}
void DeQueue(QLink *Q, int *i)
{
QNode *p;
if(Q->front == Q->rear)
{
Error("empty queue!");
exit(0);
}
p = Q->front->next;
*i = p->data;
Q->front->next = p->next;
if(p == Q->rear)
Q->rear = Q->front;
free(p);
}
void GetHead(QLink *Q, int *i)
{
if(Q->front == Q->rear)
{
Error("empty queue!");
exit(0);
}
*i = Q->front->next->data;
}
int EmptyQueue(QLink *Q)
{
if(Q->front == Q->rear)
return 1;
else
return 0;
}
int GetLength(QLink *Q)
{
QPtr p=Q->front;
int i=0;
while(p != Q->rear)
{
i++;
p = p->next;
}
return i;
}
int main()
{
QLink Q;
int i, t;
InitQueue(&Q);
for(i=0; i<5; i++)
EnQueue(&Q, i+1);
GetHead(&Q, &t);
printf("%d\n", GetLength(&Q));
ClearQueue(&Q);
DeQueue(&Q, &t);
printf("%d ", t);
DestroyQueue(&Q);
return 0;
}
阅读(835) | 评论(0) | 转发(0) |