#define MAXSIZE 100
#include<stdio.h>
#include <cstdlib>
typedef struct {
int data;
}Qlemtype;
typedef struct {
Qlemtype data;
Qlemtype* base;//为了动态分配数组,指向分配后数组的首地址
int front;
int rear;
}SqQueue;
void initqueue(SqQueue& Q);
void length(SqQueue Q);
void enqueue(SqQueue& Q,int s);
void tarverseQueue(SqQueue Q);
void outqueue(SqQueue& Q);
int main(){
printf("input your queue length:\n");
int x;
SqQueue Q;
scanf_s("%d", &x);
initqueue(Q);
length(Q);
enqueue(Q, x);
length(Q);
tarverseQueue(Q);
outqueue(Q);
length(Q);
tarverseQueue(Q);
}
//初始化,分配数组空间。
void initqueue(SqQueue& Q) {
//Q.base = new Qlemtype[MAXSIZE];
Q.base = (Qlemtype*)malloc(MAXSIZE * sizeof(Qlemtype));
if (!Q.base)
exit;
else
Q.front = Q.rear=0;
}
//求循环队列的长度
void length(SqQueue Q) {
int x;
x = (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
printf("the queue length is %d\n", x);
}
//入队
void enqueue(SqQueue& Q,int s) {
//if ((Q.rear + 1) % MAXSIZE == Q.front)
// printf("the queue is full!");//异常处理
for (int i = 0; i < s; i++){
printf("please input the %d number:\n", i + 1);
scanf_s("%d", &((Q.base[Q.rear]).data));
Q.rear = (Q.rear + 1) ;//
}
}
void outqueue(SqQueue& Q) {
int x;
if (Q.front == Q.rear)
printf("the queue is empty!\n");
else {
printf("please enter the quantity that you want to delete:\n");
scanf_s("%d", &x);
for (int i = 0; i < x; i++) {
Q.front = (Q.front + 1) % MAXSIZE;
}
}
}
//错误的写法,出现的结果会是队尾的数据没了,原因是从base[0]处开始打印,而在删除过程中,只是移动指针并未删除数据。
//void Printf(SqQueue Q) {
// printf("current queue is \n");
// int x= (Q.rear - Q.front + MAXSIZE) % MAXSIZE;
// for (int j = 0; j < x; j++) {
// printf(" %d", Q.base[j].data);
// }
// printf("\n");
//}
// 遍历队列操作
void tarverseQueue(SqQueue Q)
{
int cur = Q.front; // 当前指针
while (cur != Q.rear) // 直到cur指向了队尾元素的下一个位置,即Q.rear,结束循环
{
printf("%d ", Q.base[cur].data);
cur = (cur + 1) % MAXSIZE; // 当前指针向后推移
}
printf("\n");
}
数据结构笔记4——顺序循环队列
最新推荐文章于 2024-07-22 19:36:52 发布