#ifndef QUEUE_H__
#define QUEUE_H__
#include"head.h"
typedef struct QueueNode{
QElementType elem;
struct QueueNode *next;
}QueueNode,*QueuePtr;
typedef struct{
QueuePtr front;
QueuePtr rear;
}linkQueue;
status initQueue(linkQueue *Q);
status destroyQueue(linkQueue *Q);
status clearQueue(linkQueue *Q);
boolean empty(linkQueue Q);
int length(linkQueue Q);
status getHead(linkQueue Q,QElementType *e);
status enQueue(linkQueue *Q,QElementType e);
status deQueue(linkQueue *Q,QElementType *e);
void traverse(linkQueue Q,void (*view)(QElementType *));
#endif
#include"Queue.h"
status initQueue(linkQueue *Q)
{
Q->front=(QueuePtr)malloc(sizeof(QueueNode));
if(!Q->front)
exit(1);
Q->rear=Q->front;
Q->front->next=NULL;
return OK;
}
status destroyQueue(linkQueue *Q)//很巧,,可以多看看
{
while(Q->front)
{
Q->rear=Q->front->next;
free(Q->front);
Q->front=Q->rear;
}
return OK;
}
status clearQueue(linkQueue *Q)
{
while(Q->front!=Q->rear)
{
QueuePtr p;
p=Q->front->next;
free(Q->front);
Q->front=p;
}
return OK;
}
boolean empty(linkQueue Q)
{
return (Q.front==Q.rear)?TRUE:FALSE;
}
int length(linkQueue Q)
{
QueuePtr p;
int i=0;
p=Q.front;
while(p!=Q.rear)
{
i++;
p=p->next;
}
return i;
}
status getHead(linkQueue Q,QElementType *e)
{
if(empty(Q))
exit(1);
*e=Q.front->next->elem;
return OK;
}
status enQueue(linkQueue *Q,QElementType e)
{
QueuePtr p;
p=(QueuePtr)malloc(sizeof(QueueNode));
if(!p)
exit(1);
p->elem=e;
p->next=NULL;
Q->rear->next=p;
Q->rear=p;
return OK;
}
status deQueue(linkQueue *Q,QElementType *e)
{
QueuePtr p;
if(empty(*Q))
exit(1);
p=Q->front->next;
*e=p->elem;
Q->front->next=p->next;
free(p);
return OK;
}
void traverse(linkQueue Q,void (*view)(QElementType *))
{
QueuePtr p;
p=Q.front->next;
while(p)
{
view(&p->elem);
p=p->next;
}
}
#include"head.h"
#include"Queue.h"
/*
status initQueue(linkQueue *Q);
status destroyQueue(linkQueue *Q);
status clearQueue(linkQueue *Q);
boolean empty(linkQueue Q);
int length(linkQueue Q);
status getHead(linkQueue Q,QElementType *e);
status enQueue(linkQueue *Q,QElementType e);
status deQueue(linkQueue *Q,QElementType *e);
void traverse(linkQueue Q,void (*view)(QElementType *));
*/
int main()
{
linkQueue Q;
QElementType e;
int i;
initQueue(&Q);
printf("the queue's address is %d\n",Q);
if(empty(Q))
printf("the queue is empty\n");
for(i=0;i<10;i++)
enQueue(&Q,i);
printf("after enQueue() the queue is :\n");
traverse(Q,view);
putchar('\n');
for(i=0;i<5;i++)
{
if(getHead(Q,&e))
printf("the first element of the queue is: %d\n",e);
deQueue(&Q,&e);
}
printf("after delete the queue is:\n");
traverse(Q,view);
putchar('\n');
if(clearQueue(&Q))
printf("the queue is cleared\n");
printf("after clear the queue the length is : %d\n",length(Q));
destroyQueue(&Q);
printf("after destroy the queue the address is :%d\n",Q);
return 0;
}
链式队列
最新推荐文章于 2024-07-13 08:21:27 发布