通过数组实现队列

来源:互联网 发布:mac欧元符号怎么打 编辑:程序博客网 时间:2024/05/06 00:09
package tt;//通过数组实现队列import java.util.NoSuchElementException;//通过数组来实现队列public class dd{// 字段public static Object[] data;// 队列的元素个数protected int size;// 队列头protected int head;// 队列尾public static int tail;/**  *   */// 无参数构造函数public dd(){final int INITIAL_LENGTH = 3;data = new Object[INITIAL_LENGTH];size = 0;head = 0;tail = -1;}// 队列元素个数方法public int size(){return size;}public boolean isEmpty(){return size == 0;}// 得到队列头元素public Object front(){if (size == 0)throw new NoSuchElementException();return data[head];}// 进入队列enqueue()方法public void enqueue(Object obj){// 此时队列已经满if (size == data.length){Object[] oldData = data;data = new Object[data.length * 2];// if(head==0)System.arraycopy(oldData, head, data, 0, oldData.length - head);if (head > 0)System.arraycopy(oldData, 0, data, head + 1, tail + 1);head = 0;tail = oldData.length - 1;}tail = (tail + 1) % data.length;size++;data[tail] = obj;}// 队列的元素出队public Object dequeue(){if (size == 0)throw new NoSuchElementException();Object ele = data[head];// 循环队列head = (head + 1) % data.length;size--;return ele;}@Overridepublic String toString(){// TODO Auto-generated method stubreturn super.toString();}}