数据结构与算法(二)--- 队列

概念

队列是遵从先进先出的有序集合。
添加新元素的一端叫对首,另一端则叫队尾

队列的实现

  • inQueue() 入队
  • outQueue() 出队
  • top() 获取队首值
  • size() 队列的长度
  • clear() 清空队列

基于数组的队列实现

class Queue {
	queue = []; // 队列数据存储
	count = 0; // 队列计数

	inQueue(val) {
		this.queue[this.count++] = val;
	}

	outQueue() {
		if(this.isEmpty()) return;
		this.count--;
		return this.queue.shift();
	}

	isEmpty() {
		return this.count === 0;
	}

	top() {
		if(this.isEmpty()) return;
		return this.queue[0]
	}
	
	size() {
		return this.count;
	}
	
	clear() {
		this.queue = []; 
		// or 
		// this.queue.length = 0;
		// this.count = 0;
	}
}

基于对象的队列实现

class Queue {
   queue =  {};
   count = 0;
   head = 0; // 用于记录队首的键
   
   inQueue(val) {
   	this.queue[this.count++] = val; 
   }

   outQueue() {
   	if(this.isEmpty()) return;
   	const headData = this.queue[this.head];
   	delete this.queue[this.head];
   	this.head++;
   	this.count--;
   	return headData;
   }
   
   isEmpty() {
   	return this.count === 0;
   }

   top() {
   	return this.queue[this.head];
   }
   
   size() {
   	return this.count;
   }
   
   clear() {
   	this.queue = {};
   	this.count = 0;
   	this.head = 0;
   }
}

双端队列

概念

可以同时从队首和队尾两端进行存取操作的队列。
与JS中的数组很相似,不同的是,双端队列不允许在数组两端以外的地方进行操作。

实现

class Deque {
	constructor() {
		this.queue = {}
		this.count = 0;
		this.head = 0;
	}
	// 队首添加
	addFront (item) {
		this.queue[--this.head] = item;
	}

  // 队尾添加
  addBack (item) {
    this.queue[this.count++] = item
  }

  // 移除队首
  removeFront () {
    if (this.isEmpty()) return;
    const headData = this.queue[this.head];
    delete this.queue[this.head++];
    return headData;
  }

  // 移除队尾
  removeBack () {
    if (this.isEmpty()) return;
    const backData = this.queue[this.count-1];
    delete this.queue[--this.count];
    return backData;
  }

  // 获取队尾值
  backTop () {
    if (this.isEmpty()) return;
    return this.queue[this.count - 1];
  }

  // 获取队首值
  frontTop() {
    if (this.isEmpty()) return;
    return this.queue[this.head];
  }

  size () {
    return this.count - this.head
  }

  isEmpty () {
    return this.size() === 0
  }
}

使用场景

队列的最大值

https://leetcode-cn.com/problems/dui-lie-de-zui-da-zhi-lcof/

滑动窗口最大值

https://leetcode-cn.com/problems/sliding-window-maximum/

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值