队列是一种列表,不同的是队列只能在队尾插入元素,在队首删除元素。队列用于存储按 顺序排列的数据,先进先出。
队列的两种主要操作是:向队列中插入新元素和删除队列中的元素。插入操作也叫做入 队,删除操作也叫做出队。入队操作在队尾插入新元素,出队操作删除队头的元素。
用数组实现的队列
function Queue() { this.dataStore = []; this.enqueue = enqueue; this.dequeue = dequeue; this.front = front; this.back = back; this.toString = toString; this.empty = empty; }
enqueue() 方法向队尾添加一个元素:
function enqueue(element) {
this.dataStore.push(element);
}
dequeue() 方法删除队首的元素:
function dequeue() {
return this.dataStore.shift();
}
front(),back() 方法读取队首和队尾的元素:
function front() { return this.dataStore[0]; } function back() { return this.dataStore[this.dataStore.length-1]; }
toString() 方法显示队列内的所有元素:
function toString() { var retStr = ""; for (var i = 0; i < this.dataStore.length; ++i) { retStr += this.dataStore[i] + " "; } return retStr; }
empty() 方法判断队列是否为空:
function empty() { if (this.dataStore.length == 0) { return true; } else { return false; } }
优先队列
在一般情况下,从队列中删除的元素,一定是率先入队的元素。从优先队列中删除元素时,需要考虑优先权的限制,在删除元素时不必遵守先进先出的约定。高优先级的元素优先处理。
重新定义 dequeue() 方法,使其删除队列中拥有最高优先级的元素。我们规定: 优先码的值最小的元素优先级最高。
function dequeue() { var priority = this.dataStore[0].code; var num = 0; for (var i = 1; i < this.dataStore.length; ++i) { if (this.dataStore[i].code < priority) { priority = this.dataStore[i].code; num = i; } } return this.dataStore.splice(num, 1); }