#include
#include
#include
typedef struct QNode
{
int data;
struct QNode *next;
}QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
void InitQueue(LinkQueue *Q)
{
Q->rear=(QueuePtr)malloc(sizeof(QNode));
Q->front = Q->rear;
if(!Q->front)
printf("memory alloc error\n");
Q->front->next=NULL;
}
void DestroyQueue(LinkQueue *Q)
{
while(Q->front)
{
Q->rear=Q->front->next;
free(Q->front);
Q->front=Q->rear;
}
}
void ClearQueue(LinkQueue *Q)
{
QueuePtr p, q;
Q->rear=Q->front;
p=Q->front->next;
Q->front->next=NULL;
while(p)
{
q=p;
p=p->next;
free(q);
}
}
void EnQueue(LinkQueue *Q, int value)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if(p==NULL)
printf("memory alloc error\n");
p->data = value;
p->next = NULL;
Q->rear->next = p;
Q->rear = p;
}
void DeQueue(LinkQueue *Q)
{
if(QueueEmpty(Q))
printf("Queue is empty");
QueuePtr p = Q->front->next;
Q->front->next = p->next;
if(Q->rear == p)
Q->rear=Q->front;
free(p);
}
int QueueEmpty(LinkQueue *Q)
{
if(Q->front->next==NULL)
return 1;
else
return 0;
}
int QueueLength(LinkQueue *Q)
{
int i=0;
QueuePtr p;
p=Q->front;
while(Q->rear != p)
{
i++;
p=p->next;
}
return i;
}
int QueueFront(LinkQueue *Q)
{
if(QueueEmpty(Q))
printf("Queue is empty\n");
return Q->front->next->data;
}
void PrintLinkQueue(LinkQueue *Q)
{
QueuePtr p;
p=Q->front->next;
while(p)
{
printf("%4d",p->data);
p=p->next;
}
printf("\n");
}
int main(void)
{
LinkQueue *Q=(LinkQueue *)malloc(sizeof(LinkQueue));
InitQueue(Q);
EnQueue(Q,1);
EnQueue(Q,2);
EnQueue(Q,3);
EnQueue(Q,4);
EnQueue(Q,5);
printf("打印该队列\n");
PrintLinkQueue(Q);
printf("该队列的长度为: %d\n", QueueLength(Q));
printf("返回队列头部的元素\n");
printf("%4d",QueueFront(Q));
printf("\n");
printf("插入一个元素6后的队列:\n");
EnQueue(Q,6);
PrintLinkQueue(Q);
printf("删除一个元素后的队列:\n");
DeQueue(Q);
PrintLinkQueue(Q);
return 0;
return i;
}
阅读(826) | 评论(0) | 转发(0) |