目录
1.链队列类型定义
1.1结点类型定义
typedef struct LNode{ //结点数据类型
int elem;
struct LNode *next;
}LNode;
1.2队列类型定义
typedef struct{ //队列数据类型
LNode *front,*rear;
}LinkQueue;
2.初始化队列
void InitQueue(LinkQueue &Q){ //初始化
Q.front=Q.rear=(LNode*)malloc(sizeof(LNode));
Q.front->next=NULL;
Q.front->elem=NULL;
}
3.入队
void EnQueue(LinkQueue &Q,int x){ //入队
LNode *p=(LNode*)malloc(sizeof(LNode));
p->elem=x;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}
4.出队
bool DelQueue(LinkQueue &Q,int &x){ //出队
if(Q.front==Q.rear)
return false;
LNode *q=Q.front->next; //头结点没有存储内容
x=q->elem;
Q.front->next=q->next;
q->next=NULL; //断链
if(q==Q.rear)
Q.rear=Q.front;
free(q);
return true;
}
5.判断队列是否为空
bool IsEmpty(LinkQueue Q){ //判空
if(Q.front==Q.rear)
return true;
else
return false;
}
6.遍历输出队列内所有元素
void PrintQueue(LinkQueue Q){ //输出
LNode *q=Q.front->next;
while(q!=NULL){
printf("%4d",q->elem);
q=q->next;
}
printf("\n");
}
7.完整代码
#include <stdio.h>
#include <stdlib.h>
typedef struct LNode{ //结点数据类型
int elem;
struct LNode *next;
}LNode;
typedef struct{ //队列数据类型
LNode *front,*rear;
}LinkQueue;
void InitQueue(LinkQueue &Q){ //初始化
Q.front=Q.rear=(LNode*)malloc(sizeof(LNode));
Q.front->next=NULL;
Q.front->elem=NULL;
}
void EnQueue(LinkQueue &Q,int x){ //入队
LNode *p=(LNode*)malloc(sizeof(LNode));
p->elem=x;
p->next=NULL;
Q.rear->next=p;
Q.rear=p;
}
bool DelQueue(LinkQueue &Q,int &x){ //出队
if(Q.front==Q.rear)
return false;
LNode *q=Q.front->next; //头结点没有存储内容
x=q->elem;
Q.front->next=q->next;
q->next=NULL; //断链
if(q==Q.rear)
Q.rear=Q.front;
free(q);
return true;
}
bool IsEmpty(LinkQueue Q){ //判空
if(Q.front==Q.rear)
return true;
else
return false;
}
void PrintQueue(LinkQueue Q){ //输出
LNode *q=Q.front->next;
while(q!=NULL){
printf("%4d",q->elem);
q=q->next;
}
printf("\n");
}
int main(){
LinkQueue Q;
int x;
InitQueue(Q);
for(;;){
scanf("%d",&x);
if(x==-1)
break;
EnQueue(Q,x);
}
PrintQueue(Q);
printf("判空:%d\n",IsEmpty(Q));
DelQueue(Q,x);
PrintQueue(Q);
printf("出队元素:%d\n",x);
return 0;
}