目录
一、数组队列(Java实现)
public class ArrayQueue<T> {
private T[] a;
private int N;
public ArrayQueue() {
a = (T[]) new Object[10];
}
// 返回队列中的元素个数
public int size() {
return N;
}
// 判断队列是否为空
public boolean isEmpty() {
return N == 0;
}
// 向队列头部插入一个元素
public void enqueue(T e) {
if(N == a.length) {
resize(a.length * 2);
}
a[N++] = e;
}
// 取出队列头部的一个元素
public T dequeue() {
T e = a[0];
for(int i = 0; i < N; i++) {
a[i] = a[i + 1];
}
N--;
if(N > 0 && N == a.length / 4) {
resize(a.length / 2);
}
return e;
}
// 查看队列头部的元素
public T getFront() {
return a[0];
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("Queue: front[");
for(int i = 0; i < N; i++) {
sb.append(a[i]);
sb.append(", ");
}
sb.delete(sb.length() - 2, sb.length());
sb.append("] tail");
return sb.toString();
}
// 扩容、缩容数组
private void resize(int newCap) {
T[] newArr = (T[]) new Object[newCap];
for(int i = 0; i < N; i++) {
newArr[i] = a[i];
}
a = newArr;
}
}
二、数组队列(JavaScript实现)
function ArrayQueue(){
let a = [];
// 动态原型模式
if(typeof this.size !== "function"){
// 返回队列中的元素个数
ArrayQueue.prototype.size = function(){
return a.length;
};
// 判断队列是否为空
ArrayQueue.prototype.isEmpty = function(){
return a.length == 0;
};
// 向队列头部插入一个元素
ArrayQueue.prototype.enqueue = function(e){
a.unshift(e);
};
// 取出队列头部的一个元素
ArrayQueue.prototype.dequeue = function(){
return a.shift();
};
// 查看队列头部的元素
ArrayQueue.prototype.getFront = function(){
return a[0];
};
// 重写toString()方法
ArrayQueue.prototype.toString = function(){
let str = "Queue: front[";
for(let i = 0; i < a.length; i++){
str += a[i] + ", ";
}
str = str.slice(0, str.length - 2);
str += "] tail";
return str;
}
}
};