java实现循环队列

来源:互联网 发布:wifi网络域名是什么 编辑:程序博客网 时间:2024/04/29 12:12
package ustc.zyy.ArrayList;public class ArrayQueue<E> { private E[] theArray; // 目前队列里数据的项目 private int currentSize; // 队列的头 private int front; // 队列的尾 private int back; private static final int DEFAULE_CAPACITY = 10; public ArrayQueue() {  // 初始化数组  theArray = (E[]) new Object[DEFAULE_CAPACITY];  // 创建空数组  makeEmpty(); } public void makeEmpty() {  // 要确保back初始化为front-1  currentSize = 0;  front = 0;  back = -1; } //下面这个私有的方法用来构建循环队列 //当x的值自增以后等于数组的长度  就将x的值设置为0 也就是回到数据的头部 private int increment(int x) {  if (++x == theArray.length)   x = 0;  return x; } public boolean isEmpty() {  return currentSize == 0; } public void enqueue(E e) {  if (currentSize == theArray.length)   doubleArray();  // 下面这个是实现循环队列的  back = increment(back);  theArray[back] = e;  currentSize++; } private void doubleArray() {  E[] newArray;  newArray = (E[]) new Object[theArray.length * 2];  for (int i = 0; i < currentSize; i++, front = increment(front))   newArray[i] = theArray[front];  theArray = newArray;  front = 0;  back = currentSize - 1; } public E dequeue() {  if (isEmpty()) {   System.err.println("错误啊");  }  currentSize--;  E returnvalue = theArray[front];  front = increment(front);  return returnvalue; } public E getFront() {  if (isEmpty()) {   System.out.print("溢出了啊");  }  return theArray[front]; }}


 

0 0
原创粉丝点击