【数据结构】队列

数据结构队列Queue

【数据结构】队列_第1张图片

function Queue() {
  // 数据存储
  this.dataStore = [];

}
Queue.prototype = {
  constructor: Queue,
  add: function(array) {
    this.dataStore = array;
  },
  // 排列
  enqueue: function( element ) {
    this.dataStore.push( element );
  },
  //随即读取
  randomData: function() {
    var index  = Math.floor(Math.random() * (this.length()-1));
    if ( index < 0 ) {
      //index = 0;
    }
    return this.dataStore.splice(index, 1);
  },
  // 出列
  dequeue: function() {
   return this.dataStore.shift();
  },
  // 读取队首
  front: function() {
    return this.dataStore[0];
  },
  // 读取队尾
  back: function() {
    return this.dataStore[this.dataStore.length - 1];
  },
  // 显示队列内所有元素
  toString: function() {
    var retStr = "";
    for ( var i = 0, length = this.dataStore.length; i< len; i++ ) {
      retStr +=  "src:" + this.dataStore[i].src + " city:" + this.dataStore[i].city + " position: " + this.dataStore[i].position;
    }
    return retStr;
  },
  // 判断队列是否为空
  empty: function() {
    if ( this.dataStore.length == 0 ) {
      return true;
    } else {
      return false;
    }
  },
  length: function() {
    return this.dataStore.length;
  }
};

你可能感兴趣的:(【数据结构】队列)