數據結構-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

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