Object
。
生活中常见的Stack的例子比如一摞书,你最后放上去的那本你之后会最先拿走;又比如浏览器的访问历史,当点击返回按钮,最后访问的网站最先从历史记录中弹出。
Stack一般具备以下方法:
以对象形式实现栈
<script type="text/javascript"> function Stack() { this.count = 0; this.storage = {}; //将一个元素推入栈顶 this.push = function (value) { this.storage[this.count] = value; this.count++; } //移除栈顶元素,并返回被移除的元素 this.pop = function () { if (this.count === 0) { return undefined; } this.count--; var result = this.storage[this.count]; delete this.storage[this.count]; return result; } //返回栈顶元素 this.peek = function () { return this.storage[this.count - 1]; } //栈中是否有元素 this.isEmpty = function () { //使用es6语法判断对象中属性长度 //return Object.keys(this.storage).length==0; return this.count==0; } //移除栈中所有元素 this.clear = function () { this.count = 0 //return this.storage={}; } //返回栈中元素的个数 this.size = function () { return this.count; } } var newStack = new Stack(); newStack.push("第一个元素"); newStack.push("第二个元素"); newStack.push("第三个元素"); console.log("打印栈中元素个数:" + newStack.size()); console.log("打印栈中栈顶元素:" + newStack.peek()); console.log("打印栈中移除元素:" + newStack.pop()); console.log("移除栈顶元素后再次打印栈中栈顶元素:" + newStack.peek()); console.log("判断栈中是否有元素:" + newStack.isEmpty()); console.log("移除栈中所有元素:" + newStack.clear()); console.log("移除后判断栈中是否有元素:" + newStack.isEmpty()); console.log("打印栈中移除元素:" + newStack.pop()); </script>
以数组形式实现栈
<script type="text/javascript"> function Stack() { //保存栈内元素的数组 this.dataStore = []; //top用来记录栈顶位置,初始化为0 this.top = 0; this.push = function (element) { this.dataStore[this.top++] = element; // 先在top位置加入元素,之后top加1 } this.pop = function () { // top先减1,然后返回top位置的元素 return this.dataStore[--this.top]; } this.peek = function peek() { return this.dataStore[this.top - 1]; } this.isEmpty = function clear() { return this.top ==0; } this.clear = function clear() { this.top = 0; } this.length = function length() { return this.top; } } var newStack = new Stack(); newStack.push("第一个元素"); newStack.push("第二个元素"); newStack.push("第三个元素"); console.log("打印栈中元素个数:" + newStack.length()); console.log("打印栈中栈顶元素:" + newStack.peek()); console.log("打印栈中移除元素:" + newStack.pop()); console.log("移除栈顶元素后再次打印栈中栈顶元素:" + newStack.peek()); console.log("判断栈中是否有元素:" + newStack.isEmpty()); console.log("移除栈中所有元素:" + newStack.clear()); console.log("移除后判断栈中是否有元素:" + newStack.isEmpty()); </script>
Queue和Stack有一些类似,不同的是Stack是先进后出,而Queue是先进先出。Queue在生活中的例子比如排队上公交,排在第一个的总是最先上车;又比如打印机的打印队列,排在前面的最先打印。
Queue一般具有以下常见方法:
Javascript中的Array已经具备了Queue的一些特性,所以我们可以借助Array实现一个Queue类型:
与栈相反,队列是一种遵循先进先出 (FIFO / First In First Out) 原则的一组有序的项;队列在尾部添加新元素,并从头部移除元素。最新添加的元素必须排在队列的末尾。·
在现实中,最常见的例子就是排队,吃饭排队、银行业务排队、公车的前门上后门下机制...,前面的人优先完成自己的事务,完成之后,下一个人才能继续。
在计算机科学中,一个常见的例子就是打印队列。比如说我们需要打印五份文档。我们会打开每个文档,然后点击打印按钮。每个文档都会被发送至打印队列。第一个发送到打印队列的文档会首先被打印,以此类推,直到打印完所有文档。·
同样的,我们在 Javascript 中实现一个队列类。
原文:https://www.cnblogs.com/zhuochong/p/11627598.html