JS中的算法与数据结构-队列(Queue)
定义
栈,它是一种比较高效的数据结构,遵循 先入后出(LIFO,last-in-first-out) 的原则。 队列,它也是一种特殊的列表,它与栈不同的是, 队列只能在队尾插入元素,在队首删除元素。
队列用于存储按顺序排列的数据,遵循 先进先出(FIFO,First-In-First-Out) 的原则
队列的属性与方法
队列的操作主要也是有两种:向队列中插入新元素和删除队列中的元素,即入队和出队操作。
| 类型 | 描述 |
|---|---|
| enqueue() | 入队,向队末插入一个元素 |
| dequeue() | 出队,删除队首一个元素 |
| front() | 读取队首元素 |
| back() | 读取队尾元素 |
| toString() | 显示所有队列中的元素 |
| clear() | 清空队列中的元素 |
| empty() | 判断队列是否为空 |
队列的实现
//定义队列
function Queue(){
this.dataStore = [];
this.enqueue = function (element) { //入队
this.dataStore.push( element );
};
this.dequeue = function() { //出队
if( this.empty() ) return 'This queue is empty';
return this.dataStore.shift();
};
this.front = function() { //查看队首元素
if( this.empty() ) return 'This queue is empty';
return this.dataStore[0];
};
this.back = function() { //查看队尾元素
if( this.empty() ) return 'This queue is empty';
return this.dataStore[this.dataStore.length-1];
};
this.toString = function() { //显示队列所有元素
console.log(this.dataStore.join('\n'));
};
this.clear = function() { //清空当前队列
delete this.dataStore;
this.dataStore = [];
};
this.empty = function() { //判断当前队列是否为空
if( this.dataStore.length == 0 ) return true;
return false;
};
}