自己实现队列

来源:互联网 发布:但做的软件程序员 编辑:程序博客网 时间:2024/05/17 06:43
public class 自己实现队列 {private static Object[] array = new Object[10];private static  int length = 0;public  void  push(T data){//入队if(length >= array.length  - 1){//当自己定义的数组长度不够时,需要扩容Object[] o = new Object[(int)(array.length * 1.5)] ;//扩大为原来的1.5倍System.arraycopy(array, 0, o, 0, length);//把原来的数据copy到心数据中array = o ;//让原来的数组array指向数组o}array[length] = data;length ++ ;}public T poll(){//实现出队T result = (T)array[0];for(int i = 0 ;i < length - 1; i++ ){array[i] = array[ i + 1]; }length --;return result;}public T peek(){//返回队顶元素,但是不出队if(length == 0 ){return null ;}else{return (T)array[0];}}public boolean isEmpty(){return length == 0;}public static void main(String[] args) {自己实现队列 queue = new 自己实现队列();queue.push("A");queue.push("B");queue.push("C");queue.push("D");queue.push("E");queue.push("F");queue.push("G");queue.push("H");queue.push("I");queue.push("J");queue.push("K");queue.push("L");queue.push("M");   while(!queue.isEmpty()){  System.out.println(queue.poll());//出队   }}}