数据结构之JavaScript实现队列(queue)

版权声明: https://blog.csdn.net/wlk2064819994/article/details/79980317

    和栈一样,队列其实也是一种列表,不同的是队列只能在队尾插入元素,在队首删除元素,也就是说,队列是先进先出的数据结构;而栈是先进后出的数据结构。队列的主要操作就是入队和出队操作,也就是队尾插入元素和队首删除元素。队列还有一个比较重要的操作就是读取队首的元素。值得注意一点的是:优先队列。优先队列的普通队列的不同是出队的规则不同:普通队列先进先出,就想排队一样;而优先队列不一定先进先出,而是按照每个元素的优先级来出队。

JavaScript实现队列代码:

<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>数据结构之JavaScript实现队列</title>
</head>
<body>
	<script>
		function Queue(){
			this.dataStore = [];
			this.enqueue = enqueue;//入队
			this.dequeue = dequeue;//出队
			this.front = front;    //读取队首元素
			this.back = back;      //读取队尾元素
			this.empty = empty;
			this.length = length;
			this.clear = clear;
			this.toString = toString;
		}

		//入队
		function enqueue(element){
		    this.dataStore.push(element);//在数组末尾添加元素
		}

		//出队
		function dequeue(){
			return this.dataStore.shift();//shift()删除数组第一个元素并返回
		}

		//读取队首元素
		function front(){
			return this.dataStore[0];
		}

		//读取队尾元素
		function back(){
			return this.dataStore[this.dataStore.length-1];
		}

		//判空
		function empty(){
			if(this.dataStore.length == 0){
				return true;
			}else{
				return false;
			}
		}

		//清空
		function clear(){
			this.dataStore = [];
		}

		//返回队列长度
		function length(){
			return this.dataStore.length;
		}

		//toString
		function toString(){
			return this.dataStore;
		}

		var que = new Queue();
		que.enqueue(1);
		que.enqueue(2);
	</script>
</body>
</html>
下面是优先队列的出队操作,其他操作都相同。
	//优先队列:其实只是出队时有点不同,优先队列不一定是先进先出,而是按照对内元素的优先级出队。
	/*假设现在队列内的元素是一个对象,有一个code属性表示其优先级,数字越小优先级有越高*/
	function previligedequeue(){
	    var entry = 0;
	    for(var i=0;i<this.dataStore.length;i++){
	    	if(this.dataStore[i].code<this.dataStore[entry].code){
	    		entry = i;
	    	}
	    }
	    return this.dataStore.splice(entry,1);
	}

猜你喜欢

转载自blog.csdn.net/wlk2064819994/article/details/79980317
今日推荐