//main.c
#include "LinkQueue.h"
#include <stdio.h>
#include <stdlib.h>
void main()
{
LinkQueue lq;
ElementType e;
InitQueue(&lq);
printf("入栈\n");
for(int i = 0; i <= 10; i++)
EnQueue(&lq, i);
printf("队列大小为%d\n", length(lq));
printf("显示\n");
Show(lq);
if (GetTop(lq, &e))
printf("队头元素为%d\n", e);
printf("出栈\n");
for(int j = 0; j < 9; j++)
DeQueue(&lq);
printf("队列大小为%d\n", length(lq));
printf("显示\n");
Show(lq);
if( GetTop(lq, &e) )
printf("队头元素为%d\n", e);
printf("清除\n");
Clear(&lq);
printf("摧毁\n");
Destroy(&lq);
system("pause");
}
//LinkQueue.h
#ifndef _LINKQUEUE_H_
#define _LINKQUEUQ_H_
#include <stdbool.h>
typedef int ElementType;
typedef struct QueueNode
{
ElementType data;
struct QueueNode *next;
}QueueNode;
typedef struct LinkQueue
{
QueueNode *first;
int size;
QueueNode *last;
}LinkQueue;
bool InitQueue(LinkQueue *lq);
bool EnQueue(LinkQueue *lq, ElementType e);
bool DeQueue(LinkQueue *lq);
void Show(LinkQueue lq);
bool GetTop(LinkQueue lq, ElementType *e);
int length(LinkQueue lq);
void Clear(LinkQueue *lq);
void Destroy(LinkQueue *lq);
#endif //_LINKQUEUE_H_
//LinkQueue.c
#include "LinkQueue.h"
#include <stdio.h>
#include <stdlib.h>
static QueueNode *CreateNode(ElementType e)
{
QueueNode *p = (QueueNode *)malloc(sizeof(QueueNode));
if( NULL != p )
{
p->next = NULL;
p->data = e;
}
return p;
}
bool InitQueue(LinkQueue *lq)
{
QueueNode *p = CreateNode(-1);
if( NULL == p )
return false;
lq->first = lq->last = p;
lq->size = 0;
return true;
}
bool EnQueue(LinkQueue *lq, ElementType e)
{
QueueNode *p = CreateNode(e);
if( NULL == p )
return false;
lq->last->next = p;
lq->last = p;
lq->size++;
return true;
}
bool DeQueue(LinkQueue *lq)
{
if( lq->first == lq->last )
{
printf("队列为空\n");
return false;
}
QueueNode *p = lq->first->next;
lq->first->next = p->next;
if( NULL == p->next ) //p为最后一个节点
{
lq->last = lq->first; //令尾指针指向头结点
}
free(p);
lq->size--;
return true;
}
void Show(LinkQueue lq)
{
QueueNode *p = lq.first->next;
while(NULL != p)
{
printf("%d\n", p->data);
p = p->next;
}
}
bool GetTop(LinkQueue lq, ElementType *e)
{
if( NULL == lq.first->next )
{
printf("队列为空\n");
return false;
}
*e = lq.first->next->data;
return true;
}
int length(LinkQueue lq)
{
return lq.size;
}
void Clear(LinkQueue *lq)
{
if( NULL == lq->first->next )
{
return ;
}
QueueNode *p = lq->first->next;
while( NULL != p)
{
lq->first->next = p->next;
free(p);
p = lq->first->next;
}
lq->size = 0;
}
void Destroy(LinkQueue *lq)
{
Clear(lq);
free(lq->first);
lq->first = lq->last = NULL;
}