Files
Course/DataStructure/test3/实验三.cpp
2025-11-07 18:39:29 +08:00

130 lines
2.6 KiB
C++
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#include <stdio.h>
#include <stdlib.h>
#define MAXSIZE 10
typedef struct Queue
{
int *data; // 存储空间的基地址
int front, rear; // 头指针、尾指针
int count; // 新增一个 count变量用于记录队中元素个数
} Queue;
// 初始化队列
void Init(Queue &Q)
{
Q.data = new int[MAXSIZE];
// todo list 处理front, rear指针以及count变量
Q.front = 0;
Q.rear = 0;
Q.count = 0;
}
// 入队
void EnQueue(Queue &Q, int e)
{
if (Q.count >= MAXSIZE) // todo list //利用count判断队是否满
printf("队满\n"); // 【有坑,思考】
else
{
// todo list //入队元素,尾指针+1
Q.data[Q.rear] = e;
Q.rear++;
// todo list //更新count值
Q.count++;
}
}
// 出队
void DelQueue(Queue &Q, int &e)
{
if (Q.count == 0) // todo list //利用count判断队是否空
printf("队空\n");
else
{
// todo list //出队元素,头指针+1
e = Q.data[Q.front];
Q.front++;
// todo list //更新count值
Q.count--;
printf("出队元素为:%d\n", e);
}
}
// 判断队空
void IsNull(Queue Q)
{
if (Q.count == 0) // todo list //利用count判断队是否空
printf("队空\n");
else
printf("队不空\n");
}
// 显示整个队列
void Display(Queue Q)
{
while (Q.count > 0)
{
printf("%3d,", Q.data[Q.front]);
// todo list //头指针依次往后移动
Q.front++;
// todo list //更新count值
Q.count--;
}
printf("\n");
}
int main()
{
Queue Q;
printf("------------------------------------\n");
printf("1.初始化队列\n");
printf("2.判断队列是否为空\n");
printf("3.入队\n");
printf("4.出队\n");
printf("5.显示整个队列\n");
printf("6.退出\n");
printf("------------------------------------\n");
int sel;
while (1)
{
printf("请输入选项:");
scanf("%d", &sel);
// getchar();
switch (sel)
{
case 1:
Init(Q);
printf("链表已经初始化。\n");
break;
case 2:
IsNull(Q);
break;
case 3:
{
int n, e;
printf("请输入入队元素个数:");
scanf("%d", &n);
printf("请输入需要入队的%d个元素:", n);
for (int i = 0; i < n; i++)
{
scanf("%d", &e);
EnQueue(Q, e);
}
}
break;
case 4:
{
int e;
DelQueue(Q, e);
}
break;
case 5:
printf("队列为:");
Display(Q);
break;
case 6:
exit(0);
}
}
}