js实现队列

队列: 队列是一种特殊的线性表,特殊性表现它只能在表的前端 front 进行删除操作,只能在表的后端 rear 进行添加操作。 先进先出(FIFO)

  1. js代码实现(链式队列的实现):
// 以构造函数的方式来实现  ,也可使用 class 来实现
funtion LinkedQueue() {
	// 定义一个节点结构
	let Node = function(ele) {   
		this.ele = ele;
		this.next = null;
	}
	let length = 0, front, rear;
	// 队尾添加操作
	this.push = function(ele) {
		let node = new Node(ele);
		if(length == 0) {
			front = node;
		} else {
			let temp = rear;
			temp.next = node;	
		}
		rear = node;
		length++;
		return true;
	}
	// 队首删除操作
	this.pop = function() {
		let temp = front;
		front = front.next;
		length--;
		temp.next = null;
		return temp;	
	}
	// 队列大小
	this.size = function() {
		return length;
	}
	// 获取头元素
	this.getFront = function() {
		return front;	
	}
	// 获取尾元素
	this.getRear = function() {
		return rear;
	}
	// 读取队列元素 toString
	this.toString = function() {
		let str = '', temp = front;
		while(temp) {
			str = str + temp.ele + ' ';
			temp = temp.next;
		}
		return str;
	}
	// 清空队列
	this.clear = function() {
		front = null;
		rear = null;
		length = 0;
		return true;
	}
}

// 测试使用
let myQueue = new LinkedQueue();
myQueue.push(1);
myQueue.push(2);
myQueue.push(3);
console.log(myQueue.toString())
console.log(myQueue.pop());
console.log(myQueue.toString())
  1. 顺序队列存储:利用js内置的Array来实现
function ArrayQueue() {
	var arr = [];
	this.push = function(ele) {
		arr.push(ele);
		return true;
	}
	this.pop = function() {
		return arr.shift();	
	}
	this.getFront = function() {
		return arr[0];
	}
	this.getRear = function() {
		return arr[arr.length - 1];
	}
	this.clear = function() {
		arr = [];
		/*
			arr.length = 0;
			arr.splice(0);
		*/
	}
	this.size = function() {
		return arr.length;
	}
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值