版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/weixin_40411915/article/details/82726497
学习参考: 严蔚敏: 《数据结构-C语言版》
基本操作
- 入队
- 出队
- 建空队列
- 判队空
- 获取队首元素
- 获取队列长度
- 清空队列
代码实现
队列结点定义
typedef struct node
{
int data;
struct node* next;
}*pNode, Node;
队列结构定义
typedef struct
{
pNode front;
pNode rear;
}* pQueue, LQueue;
建空队列
int initQueue(pQueue q)
{
if(!q)
return 0;
q->front = q->rear = NULL;
return 1;
}
判队空
int queueEmpty(pQueue q)
{
int tag = 0;
if(!q)
return 0;
tag = (q->front==NULL && q->rear == NULL);
return tag;
}
入队
int enQueue(pQueue q, int data)
{
pNode node = NULL;
if(!q)
return 0;
node = (pNode)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
if(queueEmpty(q))
q->front=q->rear=node;
else
{
q->rear->next = node;
q->rear = node;
}
return 1;
}
出队
int deQueue(pQueue q, int* val)
{
pNode p = NULL;
if(!q || queueEmpty(q))
return 0;
p = q->front;
*val = p->data;
q->front = p->next;
if(q->rear == p)
q->rear=NULL;
free(p);
p = NULL;
return 1;
}
获取队列长度
int QueueLength(pQueue q, int* len)
{
pNode p = NULL;
int count = 1;
if(!q)
return 0;
p = q->front;
while(p)
{
if(p==q->rear)
break;
p = p->next;
}
if(!p)
count = 0;
*len = count;
return 1;
}
获取队首元素
int getHead(pQueue q, int* val)
{
pNode p = NULL;
if(!q || queueEmpty(q))
return 0;
p = q->front;
*val = p->data;
return 0;
}
清空队列
int clearQueue(pQueue q)
{
pNode p = NULL, pre = NULL;
int count = 1;
if(!q)
return 0;
p = q->front;
while(p)
{
pre = p;
p = p->next;
free(pre);
pre=NULL;
}
q->front = q->rear = NULL;
return 0;
}
测试代码
#include <stdio.h>
#include "ListQueue.h"
int main()
{
LQueue Q;
int i=0;
int val= -1;
initQueue(&Q);
for(i=1; i<11; ++i)
enQueue(&Q, i);
deQueue(&Q, &val);
printf("%d... \n", val);
getHead(&Q, &val);
printf("%d... \n", val);
clearQueue(&Q);
return 0;
}
写在最后
文章记录本人学习所得, 如有所错误, 欢迎留言指出交流, 大神请键盘下留人 ! ! !