数据结构之队列

JavaScript实现队列

  • 队列数据结构
  • 创建队列
  • 向队列添加元素
  • 从队列移除元素
  • 查看队列头元素
  • 查看队列是否为空
  • 打印队列元素

1. 队列数据结构

栈是一种遵从先进先出(FIFO)原则的一组有序的项。队列在尾部添加新元素,并从头部移除元素。最新添加的元素必须排在队列的末尾。

2. 创建队列

创建一个类来表示栈。

function Queue() {
	let items = [];
}

3. 向队列添加元素

实现一个push方法

this.enqueue = function(element){
	items.push(element);
};

4. 从队列移除元素

this.dequeue = function() {
	return items.shift():
};

5. 查看队列头元素

this.front = function() {
	return items[0];
};

6. 检查队列是否为空

this.isEmpty = function() {
	return items.length === 0;
};
// 返回栈的length
this.size = function() {
	return items.length;
};

7. 打印队列元素

this.print= function() {
	console.log(items.toString());
};

完整代码


function Queue() {
	let items = [];
	
	this.push = function(element){
		items.push(element);
	};
	
	this.enqueue = function(element){
		items.push(element);
	};
	this.dequeue = function() {
		return items.shift():
	};
	
	this.front = function() {
		return items[0];
	};
		
	this.isEmpty = function() {
		return items.length === 0;
	};
	// 返回栈的length
	this.size = function() {
		return items.length;
	};
	this.print= function() {
		console.log(items.toString());
	};
};

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值