java实现循环队列

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];
 }

}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值