#include <stdio.h>
#include<malloc.h>
typedef char ElemType;
typedef struct qnode
{
int data;
struct qnode *next;
}QNode;
typedef struct
{
QNode *front;
QNode *rear;
}LiQueue;
//初始化队列
void InitQueue(LiQueue *&q)
{
q=(LiQueue*)malloc(sizeof(LiQueue));
q->front=q->rear=NULL;
}
//判断是否为空
int QueueEmpty(LiQueue *q)
{
if(q->rear==NULL)
return 1;
else
return 0;
}
//释放
void ClearQueue(LiQueue *q)
{
QNode *p=q->front,*r;
if(p!=NULL)
{
r=p->next;
while(r!=NULL)
{
free(p);
p=r;r=p->next;
}
}
free(q);
}
//实现队列的入队
void enQueue(LiQueue *q,int e)
{
//封装结点
QNode *s;
s=(QNode*)malloc(sizeof(QNode));
s->data =e;
s->next=NULL;
if(q->rear==NULL)
{
q->front =s;
q->rear =s;
}
else
{
q->rear->next =s;
q->rear =s;
}
}
//出队函数
int deQueue(LiQueue *q,ElemType &e)
{
QNode *t;
if(q->rear ==NULL)
return 0;
if(q->front ==q->rear )//只有一个结点
{
t=q->front ;
q->front =NULL;
q->rear =NULL;
}
else
{
t=q->front;
q->front=q->front->next;
}
e=t->data;
free(t);
return 1;
}
//实现队列的测长
int length(LiQueue *q)
{
int n=0;
qnode *p;
p=q->front ;
while(p!=NULL)
{
p=p->next;
n++;
}
return n;
}
void main()
{
ElemType e;
LiQueue *q;
printf("初始化队列q/n");
InitQueue(q);
printf("依次进入队列元素a,h,c/n");
enQueue(q,'a');
enQueue(q,'h');
enQueue(q,'c');
enQueue(q,'d');
printf("队列为%s/n",(QueueEmpty(q)?"空":"非空"));
if(deQueue(q,e)==0)
printf("队空不能出对/n");
else
printf("出对一个元素%c/n",e);
printf("队列的元素个数:%d/n",length(q));
printf("释放队列/n");
ClearQueue(q);
}
队列的链表实现!
最新推荐文章于 2022-02-23 15:02:25 发布