数据结构:队列的链式存储(带头结点)
1.结点的数据结构
2.队列的数据结构
3.初始化
4.入队操作
5.出队操作
6.判空操作
7.读队头元素
8.测试
9.输出结果
所用编译器:Visual Studio Code 1.42.1 C++环境
#include <stdio.h>
#include <stdlib.h>
typedef int Elemtype;
//结点的数据结构
typedef struct LinkNode{
Elemtype data;
struct LinkNode *next;
}LinkNode;
//队列的数据结构
typedef struct{
LinkNode *front,*rear;
int length; //用于记录队列的长度
}LinkQueue;
//初始化
void InitQueue(LinkQueue &Q){
Q.front=Q.rear=(LinkNode *)malloc(sizeof(LinkNode));
Q.front->next=NULL;
Q.length=0;
}
//入队操作
bool EnQueue(LinkQueue &Q,Elemtype x){
LinkNode *s=(LinkNode *)malloc(sizeof(LinkNode));
s->data=x;
s->next=NULL;
Q.rear->next=s;
Q.rear=s;
Q.length++;
return true;
}
//出队操作
bool DeQueue(LinkQueue &Q,Elemtype &x){
if(Q.front==Q.rear)
return false;
LinkNode *p=Q.front->next;
x=p->data;
Q.front->next=p->next;
if(Q.rear==p)
Q.rear=Q.front;
free(p);
Q.length--;
return true;
}
//判空操作
bool IsEmpty(LinkQueue Q){
return(Q.front==Q.rear);
}
//读队头元素
bool GetHead(LinkQueue Q,Elemtype &x){
if(Q.front==Q.rear)
return false;
x=Q.front->next->data;
return true;
}
//测试
int main(){
LinkQueue Q;
InitQueue(Q);
Elemtype a,b,c;
//入队几个元素并打印队列长度
EnQueue(Q,3);
EnQueue(Q,5);
EnQueue(Q,9);
EnQueue(Q,6);
printf("Q.length=%d\n",Q.length);
//出队几个元素并打印
DeQueue(Q,a);
DeQueue(Q,b);
printf("a=%d\n",a);
printf("b=%d\n",b);
//读当前队头元素并打印
GetHead(Q,c);
printf("c=%d\n",c);
//判断当前队列是否为空
if(IsEmpty(Q))
printf("当前队列为空\n");
else
printf("当前队列不为空\n");
//将剩余元素删除后再判空
DeQueue(Q,a);
DeQueue(Q,b);
if(IsEmpty(Q))
printf("当前队列为空\n");
else
printf("当前队列不为空\n");
}
//输出结果
Q.length=4
a=3
b=5
c=9
当前队列不为空
当前队列为空