欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

js 队列 先进先出

程序员文章站 2022-03-01 18:09:38
...

队列

		function Queue() {
			// var items = []
			window.items = [] // 方便调试
			this.enqueue = function (e) {
				items.push(e)
			}

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

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

			this.isEmpty = function (e) {
				return items.length == 0
			}

			this.size = function (e) {
				return items.length
			}

			this.clear = function (e) {
				items = []
			}

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

根据优先级插入元素

	function PriorityQueue(){
			var items = []
			function QueueE(e, priority){
				this.e = e
				this.priority = priority
			}

			this.enqueue = function(e, priority){

				let queueE = new QueueE(e, priority)

				if(this.isEmpty()){
					items.push(queueE)
				}

				for(let i = 0;i<items.length;i++){
					let isAdd = false
					if(queueE.priority < items[i].priority){
						items.splice(i,0,queueE)
						isAdd = true
					}
					if(!isAdd){
						items.push(queueE)
					}
				}
			}	
		}
相关标签: js