Files
studycode/datastructure/2025301205+施光甲+实验三.cpp
2025-12-03 23:08:39 +08:00

137 lines
2.8 KiB
C++
Raw Permalink 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];
//处理front, rear指针以及count变量
Q.front = 0;
Q.rear = 0;
Q.count = 0;
}
//入队
void EnQueue(Queue &Q, int e)
{
if (Q.count == MAXSIZE) //利用count判断队是否满
printf("队满\n");
else {
//入队元素,尾指针+1
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE; //循环队列,需要取模
//更新count值
Q.count++;
printf("元素%d入队成功\n", e);
}
}
//出队
void DelQueue(Queue &Q, int &e)
{
if (Q.count == 0) //利用count判断队是否空
printf("队空\n");
else{
//出队元素,头指针+1
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MAXSIZE; //循环队列,需要取模
//更新count值
Q.count--;
printf("出队元素为:%d\n", e);
}
}
//判断队空
void IsNull(Queue Q)
{
if (Q.count == 0) //利用count判断队是否空
printf("队空\n");
else
printf("队不空\n");
}
//显示整个队列
void Display(Queue Q)
{
if (Q.count == 0) {
printf("队列为空\n");
return;
}
int tempFront = Q.front; // 使用临时变量,避免修改原队列
int tempCount = Q.count; // 使用临时计数
while (tempCount > 0)
{
printf("%3d,", Q.data[tempFront]);
tempFront = (tempFront + 1) % MAXSIZE; // 临时指针后移
tempCount--; // 临时计数减1
}
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);
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);
default:
printf("无效选项\n");
}
}
return 0;
}