数据结构-07 队列

1、代码模拟:

package org.gzw.ch03;
/**
 * 队列
 */
public class MyQueue {
	//底层试用数组
	private long[] arr;
	//有效数据的长度
	private int elements;
	//对头
	private int front;
	//队尾
	private int end;

	/**
	 * 默认无参构造
	 */
	public MyQueue(){
		arr = new long[10];
		elements = 0;
		front = 0;
		end = -1;
	}
	
	/**
	 * 带参数的构造方法
	 */
	public MyQueue(int maxsize){
		arr = new long[maxsize];
		elements = 0;
		front = 0;
		end = -1;
	}
	
	/**
	 * 添加数据,从队尾插入
	 */
	public void insert(long value){
		arr[++end] = value;
		elements++;
	}
	
	/**
	 * 删除数据,从队头删除???
	 */
	public long remove(){
		elements--;
		return arr[front++];
	}
	
	/**
	 * 查看数据,从队头查看
	 */
	public long peek(){
		return arr[front];
	}
	
	/**
	 * 判断是否为空
	 */
	public boolean isEmpty(){
		return elements == 0;
	}
	
	/**
	 * 判断是否满了
	 */
	public boolean isFull(){
		//return (end - front) == arr.length;
		return elements == arr.length;
	}
}

2、测试:

package org.gzw.ch03;

public class TestMyQueue {

	public static void main(String[] args) {
		MyQueue myQueue = new MyQueue(4);
		myQueue.insert(23);
		myQueue.insert(45);
		myQueue.insert(13);
		myQueue.insert(1);
		
		System.out.println(myQueue.isEmpty());
		System.out.println(myQueue.isFull());
		System.out.println(myQueue.peek());
		System.out.println(myQueue.peek());
		
		while(!myQueue.isEmpty()){
			System.out.print(myQueue.remove() + ", ");
		}
		System.out.println();
		System.out.println(myQueue.isFull());
		System.out.println(myQueue.isEmpty());
		
		//这里会报错,原因是end位置在最下面,再插入就会有错。
		myQueue.insert(20);

	}

}


3、运行结果:

false
true
23
23
23, 45, 13, 1, 
false
true
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 4
	at org.gzw.ch03.MyQueue.insert(MyQueue.java:39)
	at org.gzw.ch03.TestMyQueue.main(TestMyQueue.java:24)


4、报错原因:insert(20)后end参数已经在数组的最后位置,在添加就会溢出,处理方法:看下一讲循环队列MyCycleQueue

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章