#include<stdio.h>
#include<stdlib.h>
#define MAXSIZE 30
/* 顺式队列 */
typedef struct QueueNode QueueNode;
struct QueueNode{
int length;//长度
int val[MAXSIZE];//存储数据
};
typedef struct QueueLink QueueLink;
struct QueueLink {
int front; //头
int rear; //尾
};
int EmptyQueue(QueueNode* p)
{
if (p->length == 0)
return 1;//队列为空
else
return 0;//队列不为空
}
int FillQueue(QueueNode* p)
{
if (p->length == MAXSIZE)
return 1;//队列满
else
return 0;//队列未满
}
void EnQueue(QueueLink* p, QueueNode* q, int num)
{
if (FillQueue(q)) {
printf_s("队列已满, 无法入队!");
return;
}
q->val[p->rear] = num;
q->length++;
p->rear = (p->rear + 1) % MAXSIZE;
return;
}
void DeQueue(QueueLink* p, QueueNode* q)
{
if (EmptyQueue(q)) {
printf_s("队列已空,无法出队!");
return;
}
printf_s("%d ", q->val[p->front]);
q->length--;
p->front = (p->front + 1) % MAXSIZE;
return;
}
int main()
{
QueueNode* q = (QueueNode*)malloc(sizeof(QueueNode));
if (!q) return NULL;
q->length = 0;
QueueLink* p = (QueueLink*)malloc(sizeof(QueueLink));
if (!p) return NULL;
p->front = 0;
p->rear = 0;
printf_s("请输入入队列的元素个数:");
int num,length;//入队元素
scanf_s("%d", &length);
printf_s("请输入入队列的元素:");
for (int i = 1; i <= length; i++) {
scanf_s("%d", &num);
EnQueue(p, q, num);
}
printf_s("出队列的元素顺序为:");
for (int i = 1; i <= length; i++)
DeQueue(p, q);
free(q);
free(p);
}
队列的顺式存储实现
最新推荐文章于 2024-08-16 21:49:16 发布