#include <stdio.h>
#include <stdlib.h>
#define OK true;
#define ERROR false;
typedef bool Status;
typedef char QElemType;
//定义队列
typedef struct QNode{
QElemType data;
struct QNode *next;
}QNode,*QueuePtr;
//定义队头,队尾
typedef struct{
QueuePtr front;
QueuePtr rear;
}LinkQueue;
//初始化队列
Status InitQueue(LinkQueue &Q){
Q.front = Q.rear = (QNode *)malloc(sizeof(QNode));
if(Q.front==NULL)return ERROR;
Q.front->next=NULL;
return OK;
}
//销毁队列
Status DestroyQueue(LinkQueue &Q){
if(Q.front==Q.rear)return ERROR;
QNode *p;
while(Q.front!=Q.rear){
p = Q.front;
Q.front=p->next;
free(p);
}
return OK;
}
//清空队列
Status ClearQueue(LinkQueue &Q){
Q.front=Q.rear;
return OK;
}
//若队列为空队列则返回TRUE,否则返回FALSE
Status QueueEmpty(LinkQueue &Q){
if(Q.front==Q.rear)return OK;
return ERROR;
}
//返回Q的元素个数,即为队列的长度
int QueueLength(LinkQueue Q){
QNode *p = Q.front;
int index = 0;
while(p->next!=NULL){
index++;
p=p->next;
}
return index;
}
//若队列不空,则用e返回Q的队头元素,并返回OK,否则返回ERROR
Status GetHead(LinkQueue Q,QElemType &e){
if(Q.front==Q.rear)return ERROR;
e = Q.front->next->data;
return OK;
}
//插入队列元素
Status EnQueue(LinkQueue &Q,QElemType e){
QNode * p = (QNode *)malloc(sizeof(QNode));
if(p==NULL)return ERROR;
p->data = e;
p->next=NULL;
Q.rear->next = p;
Q.rear = p;
return OK;
}
//删除队列元素,若队列不空,则删除Q的队头元素,则用e返回其值,并返回OK,否则返回ERROR
Status DeQueue(LinkQueue &Q,QElemType &e){
if(Q.front==Q.rear)return ERROR;
QNode *p = Q.front->next;
e = p->data;
Q.front->next=p->next;
free(p);
return OK;
}
int main(){
LinkQueue Q;
QElemType e='1';
//初始化队列
Status status = InitQueue(Q);
printf("%d\n",status);
//入队
Status s = EnQueue(Q,'a');
printf("入队:%d\n",s);
s = EnQueue(Q,'b');
printf("入队:%d\n",s);
s = EnQueue(Q,'c');
printf("入队:%d\n",s);
//判断队列长度
printf("队列长度:%d\n",QueueLength(Q));
//返回队头元素
GetHead(Q,e);
printf("返回队头元素:%c\n",e);
//删除队列元素
DeQueue(Q,e);
printf("删除队列元素:%c\n",e);
//判断队列长度
printf("队列长度:%d\n",QueueLength(Q));
//清空队列
printf("清空队列:%d\n",ClearQueue(Q));
//判断是否为空队列
printf("是否为空队列:%d\n",QueueEmpty(Q));
return 0;
}
链式队列的一些基本操作(如有不对请指正)
最新推荐文章于 2021-12-14 21:51:47 发布