数据结构笔记4——顺序循环队列

#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");

}

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值