要创建一个队列,首先要对队列的定义完全掌握,队列是一种受限制的线形表,只能表头出队列,表尾进队列。那么我们在创建队列时,要牢牢把握这一特性,每新增一个元素进队列时,队尾指针都要向后移一位,而队首指针不动指向第一个元素,以此类推。
注意:在第一个元素进队列时,队首指针和队尾指针都要指向第一个元素。
以下是代码实现:
#include <stdio.h>
#include <stdlib.h>
//链式队列
typedef struct Queue{
int data;
struct Queue *top;
struct Queue *base;
}Queue;
//初始化
void InitQueue(Queue *p){
p->top=p->base=NULL;
}
//进队列
void EnQueue(Queue *l,int elem){
Queue *p=(Queue*)malloc(sizeof(Queue));
if (p==NULL){
printf("分配失败");
return;
}
p->data=elem;
p->base=NULL;
if (l->top==NULL){
l->top=l->base=p;
} else{
l->base->base=p;
l->base=p;
}
}
//出队列
void DeQueue(Queue *l){
if (l->top==NULL && l->base==NULL){
printf("出队列失败");
return;
} else{
Queue *temp=l->top;
l->top=l->top->base;
free(temp);
}
}
//取队列第一个元素
void GetHead(Queue *l){
if (l->top==NULL && l->base==NULL){
printf("队列为空,取值失败");
return;
} else{
printf("队首元素为:%d\n",l->top->data);
}
}
//队列长度
void LengthQueue(Queue *l){
if (l->top==NULL && l->base==NULL){
printf("队列为空");
return;
} else{
int count=0;
Queue *temp=l->top;
while (temp!=NULL){
count++;
temp=temp->base;
}
printf("队列长度为:%d\n",count);
}
}
//遍历队列元素,分别输出
void PrintQueue(Queue *l){
if (l->top==NULL && l->base==NULL){
printf("队列为空");
return;
} else{
Queue *temp=l->top;
printf("队列中有元素:");
while (temp!=NULL){
printf("%d\t",temp->data);
temp=temp->base;
}
}
}
int main(){
Queue p;
InitQueue(&p);
EnQueue(&p,10);
EnQueue(&p,80);
EnQueue(&p,90);
GetHead(&p);
LengthQueue(&p);
PrintQueue(&p);
}