java循环队列_Java实现循环队列

一、分析

队列是一种先进先出的线性表,它只允许在表的一端进行插入,而在另一端删除元素。允许插入的一端称为队尾,允许删除的一端称为队头。

循环队列是一种以顺序存储结构表示的队列,为了解决“假溢出”问题而将它设计成头尾相接的循环结构,它的基本操作如下:

1、初始化循环队列

2、销毁循环队列

3、清空循环队列

4、检测循环队列是否为空

5、返回循环队列的元素个数

6、返回循环队列头元素

7、向队尾插入元素

8、删除并返回队头元素

9、遍历循环队列

在循环队列中,除了用一组地址连续的存储单元依次存储从队头到队尾的元素外,还需要附设两个整型变量front和rear分别指示队头和队尾的位置。

在Java中,我们可以将循环队列视作一个类,通过成员变量数组来表示一组地址连续的存储单元,再定义两个成员变量front和rear,将循环队列的基本操作定义成类的方法,循环效果则用“模”运算实现,以此来实现循环队列。这样,初始化循环队列就是将类实例化,销毁就是销毁实例化出来的对象。

二、实现

1、定义类属性和构造函数

1 classInitQueue{2

3 private int [] queue = null;4

5 private int front = 0;6

7 private int rear = 0;8

9 private boolean empty = true;     //true表示循环队列为空

10

11 public InitQueue(int max) {      //构造指定大小的循环队列

12 this.queue = new int[max];13 }14 }

2、清空循环队列

1 public voidclearQueue() {2 this.front = 0;3 this.rear = 0;4 this.empty = true;5 }

3、检测循环队列是否为空

1 public booleanqueueEmpty() {2 if(this.empty == true) {3 return true;4 }else{5 return false;6 }7 }

4、返回循环队列的元素个数

1 public intqueueLength() {2 if (this.front == this.rear && this.empty == false) {3 return this.queue.length;                             //如果循环队列已满,返回数组长度即元素个数

4 }5 return (this.rear - this.front + this.queue.length) % this.queue.length;   //否则,取模运算得到长度

6 }

5、返回循环队列头元素

1 public int[] getHead() {2

3 if (this.empty == true) {4 return null;5 }6

7 int [] i = new int[1];8 i[0] = queue[this.front];9 returni;10 }

6、向队尾插入元素

1 public boolean enQueue(intvalue) {2

3 if (this.empty == false && this.front == this.rear) {4 return false;5 }6

7 this.queue[this.rear] =value;8 this.rear = (this.rear + 1) % this.queue.length;9 this.empty = false;10 return true;11 }

7、删除并返回队头元素

1 public int[] deQueue() {2

3 if (this.empty == true) {4 return null;5 }6

7 int [] i = new int[1];8 i[0] = this.queue[this.front];               //获取队头元素

9

10 this.front = (this.front + 1) % this.queue.length;   //删除队头元素(front指针加一)

11

12 if(this.front == this.rear) {                //如果循环队列变空,改变标志位

13 this.empty = true;14 }15 returni;16 }

8、遍历循环队列

1 public String queueTraverse() {                   //此处用输出循环队列表示遍历

2

3 String s = "";4 int i = this.front;                        //i指向第一个元素

5

6 if(this.front == this.rear && this.empty == false) {    //如果循环队列已满,取出第一个元素,i指向下一个元素

7 s += this.queue[i] + "、";8 i = (i + 1) % this.queue.length;9 }10

11 while (i != this.rear) {                     //如果未到末尾,则循环读取元素

12 s += this.queue[i] + "、";13 i = (i + 1) % this.queue.length;14 }15

16 if(s.length() == 0) {                       //如果没有读取到元素,直接返回空字符串

17 returns;18 }19 return s.substring(0,s.length() - 1);             //除去最后的顿号返回

20 }

三、小结

以上就是循环队列用Java的实现,由于只定义了整数的数组,因此只能操作整数数据,但循环队列的基本思想都已实现。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值