数据结构之 - queue

34 阅读1分钟
let Queue = function () {
  let items = [];
  this.enqueue = function (ele) {
    items.push(ele);
  };
  this.getItems = function () {
    return items;
  };
  this.dequeue = function () {
    return items.shift();
  };
  this.peek = function () {
    return items[0];
  };
  this.isEmpty = () => {
    return items.length === 0;
  };
  this.clear = () => {
    items = [];
  };
  this.size = () => {
    return items.length;
  };
};

// 击鼓传花
// 谁拿着花,谁就在队列头

let flowers = function (user, number) {
  let q = new Queue();
  for (let i = 0; i < user.length; i++) {
    q.enqueue(user[i]);
  }

  let exit;
  while (q.size() > 1) {
    for (let i = 0; i < number - 1; i++) {
      q.enqueue(q.dequeue());
    }
    exit = q.dequeue();
  }
  return q.dequeue();
};

// 优先队列 priorityQueue

let priorityQueue = function () {
  let items = [];

  // 辅助类
  let CreateUser = function (name, zIndex) {
    this.name = name;
    this.zIndex = zIndex;
  };

  this.enqueue = function (ele, zIndex) {
    let queueItem = new CreateUser(ele, zIndex);

    let isSuccess = false;

    for (let i = 0; i < items.length; i++) {
      if (queueItem.zIndex > items[i].zIndex) {
        items.splice(i, 0, queueItem);
        isSuccess = true;
        return;
      }
    }
    if (!isSuccess) {
      items.push(queueItem);
    }
  };
};