ArrayQueue的底层实现

package zy813ture;

public class MyArrayQueue1 {//双向循环数组

	private Object []obj;
	private int front;
	private int last;
	//private int MAXQSIZE;
	
	public MyArrayQueue1() {
		obj = new Object[4];
	}

	public boolean offer(Object element) {// 将指定的元素插入此队列
		if(element==null)
			 throw new NullPointerException ("元素为null");
		
		if(last==front && obj[front] !=null){    //判断此队列是否队满
			return false;
		}
		
		obj[last] = element;
		last = (last + 1) % obj.length;
		return true;
		
	}
	
	public Object peek(){// 获取不移除此队列的头;如果此队列为空,则返回 null
		if(last == front && obj[front] == null)   //判断此队列是否为空
			return null;
		
		return obj[front];
	}

	public Object poll(){// 获取并移除此队列的头;如果此队列为空,则返回 null
		if(last == front && obj[front] == null)   //判断此队列是否为空
			return null;
		Object o = obj[front];//定义个o放置第一个
		obj[front]=null;//移除
		front=(front+1)%obj.length;//移除第一个后front变成front+1;
		return o;
		}
	
	public static void main(String[] args) {
		MyArrayQueue1 me= new MyArrayQueue1();
	    me.offer("ab1");
		me.offer("ab2");
		me.offer("ab3");
		//System.out.println(me.peek());// ab1 空的话为null
		//System.out.println(me.poll());// ab1 空的话为null
		//System.out.println(me.peek());// ab2 空的话为null
		System.out.println(me.peek());// ab2 空的话为null
        
	}

}

  

转载于:https://www.cnblogs.com/ysg520/p/9471650.html

你可能感兴趣的:(ArrayQueue的底层实现)