js---数据结构学习第四日--队列的实现

队列:

队列是遵循先进先出的一组有序的项
在队列尾部添加新元素,并从顶部移除元素,最常见的例子就是排队。

创建队列
function Queue(){
var items=[];    
 //从队列尾部添加元素
 this.enqueue=function(element){
  item.push(element);
};
//从队列头部移除元素
this.dequeue=function(){
    return items.shift();
};
//返回队列最前面的元素
this.front=function(){
   return items[0];
 }
 //判断队列是否为空
 this.isEmpty=function(){
   return items.length==0;
  }
  //清空队列
  this.clear=function(){
      items=[];
   };
   //获取队列元素个数
  this.size = function () {
      return items.length;
  };
  //打印该队列
  this.print = function () {
      console.log(items.toString())
  };
}
    const queue = new Queue();
    console.log(queue.isEmpty()); // outputs true
    queue.enqueue('John');
    queue.enqueue('Jack');
    queue.print(); // John,Jack

优先队列:

根据优先级对队列排序。
//声明Queue类
function PriorityQueue() {
//声明并初始化一个用来存放队列元素的数组。
let items = [];
//创建一个拥有优先级的元素类
function QueueElement(element,priority) {
this.element = element;
this.priority = priority;
}
//添加队列元素
this.enqueue = function (element,priority) {
let queueElement = new QueueElement(element,priority);
let added = false;
//遍历队列元素,1的优先级最高,一次类推,如果当前元素优先级大于items[i],那么就把该元素放在items[i]前面。
//splice方法的第二的参数如果为0,那么则把第三个参数添加到i前面。
for(let i = 0; i < items.length; i++) {
if(queueElement.priority < items[i].priority) {
items.splice(i,0,queueElement);
added = true;break;
}
}
// 通过added判断是否可以直接把元素入列。
if(!added) {
items.push(queueElement);
}
};
//移除并返回该队列元素
this.dequeue = function () {
return items.shift();
};
//获取队列头部元素
this.front = function () {
return items[0];
};
//判断队列元素是否为空
this.isEmpty = function () {
return items.length == 0;
};

//获取队列元素个数
this.size = function () {
return items.length;
};
//循环打印元素及其优先级“`”是ES6的模板字符串
this.print = function () {
for(let i = 0; i < items.length; i++) {
console.log(
${items[i].element} - ${items[i].priority}`);
}
};
}
const queue = new PriorityQueue();
console.log(queue.isEmpty()); // outputs true

queue.enqueue(‘zaking’,2);
queue.enqueue(‘linbo’,6);
queue.enqueue(‘queue’,5);

queue.print();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

达芬绿瓶小

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

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

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

打赏作者

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

抵扣说明:

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

余额充值