数据结构-队列和优先级队列

一、队列

function Queue() {
	// 创建一个队列的容器
	this.container = [];
}
Queue.prototype = {
	constructor: Queue,
	// 进入队列  element进入队列的元素
	enter: function enter(element) {
		this.container.push(element);
	},
	// 移除队列
	leave: function leave() {
		if (this.container.length === 0) return;
		return this.container.shift();
	},
	// 查看队列的长度
	size: function size() {
		return this.container.length;
	},
	// 查看队列的内容
	value: function value() {
		// 深度克隆是为了保证后期外面接收到的结果不论如何的操作都不会影响内部容器中的内容
		// this.container.slice(0) 浅拷贝
		// JSON.parse(JSON.stringify(this.container)) 深拷贝
		return JSON.parse(JSON.stringify(this.container));
	}
};

二、优先级队列

function Queue() {
	this.container = [];
}
Queue.prototype = {
	constructor: Queue,
	// 进入队列  priority优先级,默认都是0,数值越大,优先级越高
	enter: function enter(element, priority = 0) {
		let obj = {
			value: element,
			priority: priority
		};
		if (priority === 0) {
			// 不指定优先级(最小优先级):存储到末尾即可
			this.container.push(obj);
			return;
		}
		// 指定优先级,我们需要从最后一项依次来比较
		let flag = false;
		for (let i = this.container.length - 1; i >= 0; i--) {
			let item = this.container[i];
			if (item.priority >= priority) {
				// 插入到比较项的后面
				this.container.splice(i + 1, 0, obj);
				flag = true;
				break;
			}
		};
		// 没有比我大的,我就是最大的,插入到容器最开始的位置即可
		!flag ? this.container.unshift(obj) : null;
	},
	// 移除队列
	leave: function leave() {
		if (this.container.length === 0) return;
		return this.container.shift();
	},
	// 查看队列的长度
	size: function size() {
		return this.container.length;
	},
	// 查看队列的内容
	value: function value() {
		return JSON.parse(JSON.stringify(this.container));
	}
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值