数据结构循环队列的插入和删除练习

#include <iostream //csdn不会正常显示,这里将>去掉了
using namespace std;
//#include<stdio.h>
//#include<stdlib.h>
#define MAXSIZE 5//只能实现四个元素插入
//不能因为下面的定义认为是
// a[0],a[1],a[2],a[3],a[4],a[5],事实上只到a[4]就结束了
//循环队列C++实现
//C语言只需要修改头文件以及cout改成printf即可
typedef struct queue {
int data[MAXSIZE];
int front;
int rear;//队尾指针不断变化
}queue;
//队列最后一个元素不写数据,用来判断满或空
//队空:front= =rear
//队满:(rear+1)%MAXSIZE==front
queue* init() {
queue* L = (queue*)malloc(sizeof(queue));
L->front = L->rear = 0;
return L;
}
int judge(queue* L) {
if (L->front == L->rear) //空
return 0;
else
if ((L->rear + 1) % MAXSIZE == L->front)
return 1;//队满
else
return -1;//非空非满
}
//FIFO
//插入元素用尾插法即队尾指针一直在移动,队首指针不变
//仅当删除时队首指针开始移动,队尾不变
void insQueue(queue* L, int data) {
if (judge(L) == 0 || judge(L) == -1) {
L->data[L->rear] = data;
int zj = L->data[L->rear];
L->rear = (L->rear + 1) % MAXSIZE;
cout << “元素:” << zj << “插入成功” << endl;
}
else {
int zj = data;
cout << “队满,” <<zj<<“插入失败” << endl;
}
}
void outQueue(queue* L) {
if (judge(L) == 0) cout<<“队空”<<endl;
else {
int data = L->data[L->front];
L->front = (L->front + 1) % MAXSIZE;
cout<<“出队的数是:”<< data<<endl;
}
}
void show(queue* L) {
if (judge(L) == 0) cout<<“队空”<<endl;
else{
int length = (L->rear - L->front + MAXSIZE) % MAXSIZE;
int i = 0, zj = L->front;//保存队首
do {
cout << L->data[zj]<<"->";
zj = (zj+1)%MAXSIZE;
} while (length>++i);
}
printf(“NULL\n”);
}
int main() {
queue* L = init();
insQueue(L, 1);
insQueue(L, 3);
insQueue(L, 5);
insQueue(L, 7);
insQueue(L, 9);
show(L);
cout << “* * * * * * * * * * * * " <<endl;
outQueue(L);
show(L);
cout << "
* * * * * * * * * * *" <<endl;
outQueue(L);
show(L);
cout<<"
* * * * * * * * * ***” <<endl;
return 0;

}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值