JavaScript 实现数据结构之---队列

队列定义:队列是一种特殊的线性表,它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作;

es5(function) 实现:

// 基于数组封装队列类
function Queue(defaultValues = []) {
  // 属性
  this.items = defaultValues;

  // 方法
  // 1.enqueue():将元素加入到队列中
  Queue.prototype.enqueue = (element) => {
    this.items.push(element);
  };

  // 2.dequeue():从队列中删除前端元素
  Queue.prototype.dequeue = () => {
    return this.items.shift();
  };

  // 3.front():查看前端的元素
  Queue.prototype.front = () => {
    return this.items[0];
  };

  // 4.isEmpty:查看队列是否为空
  Queue.prototype.isEmpty = () => {
    return this.items.length === 0;
  };

  // 5.size():查看队列中元素的个数
  Queue.prototype.size = () => {
    return this.items.length;
  };

  // 6.toString():将队列中元素以字符串形式输出
  Queue.prototype.toString = () => {
    let resultString = '';
    for (let i of this.items) {
      resultString += `${i}`;
    }
    return resultString;
  };

  // 打印
  Queue.prototype.print = () => {
    console.log(this.items.toString());
  };
}

es6(class)实现:

// 基于数组封装队列类
class Queue {
  constructor(defaultValues = []) {
    // 属性
    this.items = defaultValues;
  }

  // 方法
  // 1.enqueue():将元素加入到队列中
  enqueue(element) {
    this.items.push(element);
  }

  // 2.dequeue():从队列中删除前端元素
  dequeue() {
    return this.items.shift();
  }

  // 3.front():查看前端的元素
  front() {
    return this.items[0];
  }

  // 4.isEmpty:查看队列是否为空
  isEmpty() {
    return this.items.length === 0;
  }

  // 5.size():查看队列中元素的个数
  size() {
    return this.items.length;
  }

  // 6.toString():将队列中元素以字符串形式输出
  toString() {
    let resultString = '';
    for (let i of this.items) {
      resultString += `${i}`;
    }
    return resultString;
  }
  // 打印
  print() {
    console.log(this.items.toString());
  }
}

const myQuene = new Queue([1, 2, 3]);
myQuene.enqueue(5);
myQuene.print();

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

superTiger_y

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值