利用動態數組實現棧的代碼就不寫了,內部就是調用了動態數組的幾個方法,仍是寫個循環隊列。數組
//隊列內元素的個數
private int size;
//隊列首元素索引位置
private int front;
//隊列末尾元素索引位置
private int tail;
private E[] data;
public LoopQueen(int capacity) {
this.size = size;
this.front = 0;
this.tail = 0;
this.data = (E[]) new Object[capacity+1];
}
/**
* 默認隊列元素的容積爲10
*/
public LoopQueen() {
this(10);
}
/**獲取隊列內的元素個數
* @return
*/
public int getSize() {
return this.size;
}
/**入隊
* @param e
*/
public void enqueen(E e) {
if ((tail+1)%data.length == front){ //隊列滿了須要擴容
resize(2*data.length);
}
data[tail] = e;
tail = (tail+1)%data.length;
size++;
}
/**隊列容積的動態擴展
* @param capacity
*/
private void resize(int capacity) {
E[] newData = (E[]) new Object[capacity+1];
for (int i = 0; i < size; i++) {
newData[i] = data[(i+front)%data.length];
}
data = newData;
front = 0;
tail = size;
}
/**出隊
* @return
*/
public E dequeen() {
if (isEmpty()){
throw new IllegalArgumentException("隊列爲空");
}
E ret = data[front];
data[front] = null;
front = (front+1)%data.length;
size--;
if (size == data.length/4 && data.length/2 != 0){
resize(data.length/2);
}
return ret;
}
public Boolean isEmpty() {
return size == 0;
}
public E getFront() {
if(isEmpty()){
throw new IllegalArgumentException("隊列內的元素個數爲0");
}
return data[front];
}
複製代碼