# Javascript与数据结构系列（二）——队列的实现

Vagor

## 队列实现

push() 方法将它的参数插入数组中第一个开放的位置,该位置总在数组的末尾,即使是个 空数组也是如此。请看下面的例子:

``````names = [];
name.push("Cynthia"); names.push("Jennifer"); print(names); // 显示 Cynthia,Jennifer
``````

``````names.shift();
``````

``````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();
}``````

``````function front() {
return this.dataStore[0];
}
function back() {
return this.dataStore[this.dataStore.length-1];
}``````

`````` function toString() {
var retStr = "";
for (var i = 0; i < this.dataStore.length; ++i) {
retStr += this.dataStore[i] + "\n";
return retStr;
}``````

``````function empty() {
if (this.dataStore.length == 0) {
return true;
}
else {
return false;
}
}``````

## 代码归纳

``````function Queue() {
this.dataStore = [];
this.enqueue = enqueue;
this.dequeue = dequeue;
this.front = front;
this.back = back;
}
this.toString = toString;
this.empty = empty;
}

function enqueue(element) {
this.dataStore.push(element);
}

function dequeue() {
return this.dataStore.shift();
}

function front() {
return this.dataStore[0];
}

function back() {
return this.dataStore[this.dataStore.length - 1];
}

function toString() {
var retStr = "";
for (var i = 0; i < this.dataStore.length; ++i) {
retStr += this.dataStore[i] + "\n";
}
return retStr;
}

function empty() {
if (this.dataStore.length == 0) {
return true;
} else {
return false;
}
}
``````

716 声望
44 粉丝
0 条评论