/*
@李德坤 烟台大学计算机与控制工程学院
我自己对链队的理解,链队的front只要不是出队操作始终指向第一个进入的元素,而rear随着元素入队由指向第一个进入的元素逐渐后移(指向下一个元素),当然front随着元素出队而逐渐后移(和rear移动方向一样)
例如
1
2 1
3 2 1
4 3 2 1
5 4 3 2 1
rear和front移动的方向都是从1到5移动
*/
#include<stdio.h>
#include<stdlib.h>
typedef int Elemtype;
typedef struct qnode//链队数据节点类型定义
{
Elemtype 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;
}
//销毁
void DestroyQueue(LiQueue *&q)
{
QNode *p=q->front,*r;
while(p!=NULL)
{
r=p->next;
while(r!=NULL)
{
free(p);
p=r;
r=p->next;
}
}
free(p);
free(q);
}
//判断队列是否为空
bool QueueEmpty(LiQueue* &q)
{
return (q->rear==NULL);
}
//入队
void enQueue(LiQueue *&q,Elemtype &e)
{
QNode *p;
p=(QNode*)malloc(sizeof(QNode));
p->data=e;
p->next=NULL;
if(q->rear==NULL)
{
q->front=q->rear=p;
}
else
{
q->rear->next=p;
q->rear=p;
}
}
//单个出队,出一次队就删掉一个
void deQueue(LiQueue* &q,Elemtype &e)
{
QNode *t;
if(q->rear==NULL)
printf("空队列!\n");
else
{
if(q->front==q->rear)
q->front=q->rear=NULL;
e=q->front->data;
t=q->front;
q->front=q->front->next;
free(t);
}
}
//输出队列所有元素
void printtQueue(LiQueue *&q)
{
QNode *p=q->front;
while(p!=NULL)
{
printf("%d ",p->data);
p=p->next;
}
}
int main()
{
int i;
LiQueue *q;
InitQueue(q);
for(i=0; i<5; i++)
{
enQueue(q,i);
printf("入队成功!\n");
}
deQueue(q,i);
printf("%d\n",i);
deQueue(q,i);
printf("%d\n",i);
//DestroyQueue(q);销毁队列
printtQueue(q);
return 0;
}
链队的操作实现
最新推荐文章于 2020-04-21 22:35:52 发布