#include<iostream>
#include<malloc.h>
using namespace std;
typedef struct qnode
{
int data;
struct qnode *next;
}LQNode;
typedef struct
{
LQNode *front; //队头
LQNode *rear; //队尾
}LQueue;
void QueueInitiate(LQueue *q) //初始化
{
q->front = NULL;
q->rear = NULL;
}
int QueueNotEmply(LQueue q) //判空
{
if (q.front == NULL)
{
return 0;
}
else
{
return 1;
}
}
void QueueAppend(LQueue *q, int x) //入队列
{
LQNode *p;
p = (LQNode *)malloc(sizeof(LQNode));
p->data = x;
p->next = NULL;
if (q->rear != NULL) //队列非空时
{
q->rear->next = p;
}
q->rear = p;
if (q->front == NULL) //队列为空时
{
q->front = p;
}
}
int QueueDelete(LQueue *q, int *x) //出队列
{
LQNode *p;
if (q->front == NULL)
{
printf("队列为空,无数据元素出队列!\n");
return 0;
}
else
{
*x = q->front->data;
p = q->front;
q->front = q->front->next;
if (q->front == NULL)
{
q->rear = NULL;
}
free(p);
return 1;
}
}
int QueueGet(LQueue q, int *x) //取队头数据元素
{
if (q.front == NULL)
{
printf("队列为空,无数据元素可取!\n");
return 0;
}
else
{
*x = q.front->data;
return 1;
}
}
int main()
{
LQueue q;
int i, x;
QueueInitiate(&q);
for (i = 0; i < 10; i++)
{
QueueAppend(&q,i+1);
}
QueueGet(q, &x);
printf("取队头数据元素:%d \n",x);
printf("依次删除队头数据元素序列:");
while (QueueNotEmply(q))
{
QueueDelete(&q,&x);
printf("%d ",x);
}
printf("\n");
return 0;
}
链队列的初始化、出队、入队、取队头元素、判空
最新推荐文章于 2024-03-21 19:32:25 发布