#include <stdio.h>
#include <stdlib.h>
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int QElemType;
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode;
typedef struct{
QNode *front;//头指针
QNode *rear;//尾指针
}LinkQueue;
//初始化
int InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QNode*)malloc(sizeof(QNode));//生成新结点作为头节点,队头和队尾指针指向此结点
if(!Q.front) exit(OVERFLOW);//判断头节点储存空间是否分配成功
Q.front->next = NULL;//头节点指针域为空
return OK;
}
//入队
int EnQueue(LinkQueue &Q, QElemType e){
QNode *p = (QNode*)malloc(sizeof(QNode));//为入队元素分配结点空间,用指针p指向
if(!p) exit(OVERFLOW);//判断节点储存空间是否分配成功
p->data = e;//将新结点的数据域置为e
p->next = NULL;//将新结点插入队尾
Q.rear->next = p;
Q.rear = p;//修改队尾指针
return OK;
}
//出队
int DeQueue(LinkQueue &Q, QElemType &e){
if(Q.front == Q.rear) return ERROR; // 判断队列是否为空
QNode *p = Q.front->next;//p指向队头元素
e = p->data;//e保存队头元素的值
Q.front->next = p->next;//修改头结点的指针域
if(Q.rear == p) Q.rear = Q.front; // 如果出队的是最后一个元素,更新rear
free(p);//释放结点p
return OK;
}
//取头元素
int GetHead(LinkQueue Q,QElemType &e){
if(Q.front==Q.rear){
return ERROR;// 判断队列是否为空
}else{
e=Q.front->next->data;//用e保存队头元素的值
return OK;
}
}
//销毁
int DestroyQueue(LinkQueue &Q){
while(Q.front){
Q.rear=Q.front->next;
free(Q.front);//释放头结点
Q.front=Q.rear;
}
return OK;
}
int main(){
LinkQueue Q;
if(InitQueue(Q)){
printf("链队列初始化完成\n");
QElemType e = 2;
if(EnQueue(Q, e)){
printf("链队列元素 %d 入队成功\n", e);
QElemType GEte;
if(GetHead(Q,GEte)){
printf("循环队列头元素为:%d\n",GEte);
QElemType e1;
if(DeQueue(Q,e1)){
printf("链队列元素 %d 出队成功\n", e1);
if(DestroyQueue(Q)){
printf("链队列销毁完成\n");
}else{
printf("链队列销毁失败\n");
}
} else {
printf("链队列出队失败\n");
}
}else{
printf("循环队列为空,无法获取队头元素\n");
}
} else {
printf("链队列入队失败\n");
}
} else {
printf("链队列初始化失败\n");
}
return 0;
}
链队列的基本操作
于 2024-04-11 09:21:39 首次发布
![](https://img-home.csdnimg.cn/images/20240711042549.png)