#include<stdio.h>
#include<stdlib.h>
队列结点类型定义
typedef struct QNode
{
int data;
struct QNode *next;
}QNode;
队列结构类型定义
typedef struct LQueue
{
QNode *front;
QNode *rear;
}LQueue;
链队初始化
void init(LQueue *&Q)
{
Q=(LQueue*)malloc(sizeof(LQueue));
Q->front=NULL;
Q->rear=NULL;
}
结点入队
void enLQueue(LQueue *&Q,int x)
{
QNode *s;
s=(QNode*)malloc(sizeof(QNode));
s->data=x;
s->next=NULL;
//rear指向最后一个元素
if(Q->rear==NULL)//链队为空,则s为队首元素
{
Q->front=Q->rear=s;
}
else
{
Q->rear->next=s;//将结点s链接入队
Q->rear=s;//尾指针后移
}
printf("%d入队\n",Q->rear->data);
}
结点出队
void outQueue(LQueue *&Q)
{
if(Q->rear==NULL)
printf("队空,出队失败\n");
else
{
//front指向第一个元素
printf("%d出队",Q->front->data);
Q->front=Q->front->next;
}
}
取队首元素
void head(LQueue *Q)
{
if(Q->front==NULL)
printf("队空,无队首元素\n");
else
{
printf("队首元素为%d",Q->front->data);
}
}
创建链队
void createLQueue(LQueue *Q)
{
int n;
printf("请输入队列元素个数\t");
scanf("%d",&n);
for(int i=0;i<n;i++)
{
int m;
scanf("%d",&m);
enLQueue(Q,m);
}
}
应用
int main()
{
LQueue *Q;
init(Q);
createLQueue(Q);
outQueue(Q);
head(Q);
return 1;
}