//链队初始化,入队,取队头元素,出队
include <stdio.h>
include <stdlib.h>
typedef struct QNode
{
int data;
struct QNode *next;
} QNode, *QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear;
} LinkQueue;
void InitQueue(LinkQueue *Q)
{
Q->front = Q->rear = (QNode *)malloc(sizeof(QNode)); //生成新结点作为头结点,队头和队尾指针指向此结点
Q->front->next = NULL; //头结点的指针域置空
}
int EnQueue(LinkQueue *Q, int e)
{
QNode *p;
p = (QNode *)malloc(sizeof(QNode)); //为入队元素分配结点空间,用指针p指向
printf("输入一个元素:");
scanf("%d", &e);
p->data = e; //将新结点数据域置为e
p->next = NULL;
Q->rear->next = p; //将新结点插入到队尾
Q->rear = p; //修改队尾指针
return 0;
}
int DeQueue(LinkQueue *Q, int *e)
{
QNode *p;
if (Q->front == Q->rear)
{
printf("队空");
}
p = Q->front->next; //p指向队头元素
*e = p->data; //e保存队头元素的值
Q->front->next = p->next; //修改头结点的指针域
if (Q->rear == p)
{
Q->rear = Q->front; //最后一个元素被删,队尾指针指向头结点
}
free(p); //释放原队头元素的空间
return 0;
}
int GetHead(LinkQueue *Q)
{
int e;
if (Q->front != Q->rear) //队列非空
{
e = Q->front->next->data; //队头元素的值,队头指针不变
}
printf("%d\n", e);
return 0;
}
int main()
{
int e;
LinkQueue *q;
InitQueue(q);
printf("入队");
EnQueue(q, e);
EnQueue(q, e);
printf("队头元素为:");
GetHead(q);
DeQueue(q, &e);
printf("出队的元素是:%d\n", e);
return 0;
}