JavaScript数据结构与算法描述-队列

队列是一种列表,只能在队尾插入元素,在队首删除元素
队列用于存储按顺序排序的数据,是种先进先出的数据结构

队列的两种主要操作是,向队列插入新元素(入队)和删除队列中的元素(出队)。另一项重要操作是读取队首元素,这个操作叫peek(),还想知道队列存储了多少元素,用length(),清空队列用clear()

底层数据存储结构是数组,push()可在数组末尾加入元素,shift()可删除数组第一个元素

function Queue(){
  this.dataStore=[]
}

队尾添加元素
Queue.prototype.enqueue=function(element){
this.dataStore.push(element)
}

队首删除元素
Queue.prototype.edqueue=function(){
  this.dataStore.shift()
}

读取队首元素
Queue.prototype.front=function(){
  return this.dataStore[0]
}

读取队尾元素
Queue.prototype.back=function(){
  return this.dataStore[this.dataStore.length-1]
}

显示队列所有元素
Queue.prototype.toString=function(){
  let retStr=''
  for(let i=0;i<this.dataStore.length;i++){
    retStr+=this.dataStore[i]+' '
  }
  return retStr
}

判断队列是否为空
Queue.prototype.empty=function(){
  return this.dataStore.length <= 0
}

原文地址:https://www.cnblogs.com/Grani/p/14354423.html