链式队列的基本操作-从创建到销毁

#include<stdlib.h>
#include<stdio.h>
//定义int的别名为QElemType
typedef int QElemType;
//链队列
typedef  struct  QNode {// 结点类型
​	QElemType data;struct QNode* next;
} QueuePtr;
typedef  struct { // 链队列数据类型
​	QueuePtr  front;  // 队头指针
​	QueuePtr  rear;   // 队尾指针
} LinkQueue; //由队头指针和队尾指针唯一确定一个队列
bool InitQueue(LinkQueue& Q) {// 构造一个空队列Q,队头指针和队尾指针都指向头结点)//QueuePtr 放在前面的一个位置,QNode放在后面的一个位置
​	Q.front = Q.rear = (QueuePtr)malloc(sizeof(QNode));if (!Q.front) return false;  //存储分配失败
​	Q.front->next = NULL;return true;
}
bool EnQueue(LinkQueue& Q, QElemType e)
{ // 插入元素e为Q的新的队尾元素
​	QueuePtr p = (QueuePtr)malloc(sizeof(QNode));     //生成新结点,起名为pif (!p)  return false;          //存储分配失败
​	p->data = e;   p->next = NULL;   //插入队尾
​	Q.rear->next = p;
​	Q.rear = p;                          //修改队尾指针指向队尾return true;
}
bool DeQueue(LinkQueue& Q, QElemType& e)
{       // 若队列不空,则删除Q的队头元素,用 e 返回其值if (Q.front == Q.rear)    return false;  //判空
​	QueuePtr p = Q.front->next;   e = p->data;         //用e返回队头元素值
​	Q.front->next = p->next;  //修改头指针始终指向队首元素if (Q.rear == p)  Q.rear = Q.front;  //特殊情况处理空队free(p);                       //释放队首结点return true;
}
/条件:队列Q已存在, 结果:队列Q被销毁,不再存在/
bool DestroyQueue(LinkQueue& Q) {if (!Q.front){return false;}while (Q.front) {
​		Q.rear = Q.front->next;free(Q.front);
​		Q.front = Q.rear;}free(Q.front);return true;
}
/ 将Q清为空队列/
void ClearQueue(LinkQueue& Q) {if (!Q.front){return;}while (Q.front) {
​		Q.rear = Q.front->next;free(Q.front);
​		Q.front = Q.rear;}
}
/ 条件:队列Q已存在, 结果:若Q为空队列,则返回TRUE,否则返回FALSE*/
bool QueueEmpty(LinkQueue& Q) {//如果为空队列。则Q.front的值为空,函数返回false
return Q.front;}
/返回Q的元素个数,即队列的长度/
 static int QueueLength(LinkQueue& Q) {int count = 0;
​	QueuePtr p = Q.front;while (p){
​		count++;
​		p = p->next;}return count;
}
/用e返回Q的队头元素/
int GetHead(LinkQueue& Q, QElemType e) {
​	QueuePtr p = Q.front;
​	e = p->next->data;return e;
}
int main()
{
​	LinkQueue Q1;if (InitQueue(Q1) == true)printf("成功创建队列Q1!\n");for (int i = 1; i < 50; i += 2)EnQueue(Q1, i);int tmp;DeQueue(Q1, tmp);printf("元素%d出队!\n", tmp);
​	QElemType e=0;printf("队列的头元素为%d \n", GetHead(Q1,e));printf("队列的长度为%d \n", QueueLength(Q1));printf("被删除的元素为%d \n", DeQueue(Q1, e));printf("此时队列的长度为%d \n", QueueLength(Q1));ClearQueue(Q1);printf("将队列置为空\n");printf("队列是否为空?%s \n",QueueEmpty(Q1) ? "否" : "是");printf("销毁队列");DestroyQueue(Q1);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值