介绍
栈(stack)结构是一种受限制的数据结构,它只能在一端添加和删除,先进的后出,后进的先出。就好比羽毛球筒,先进去的永远是最后一个出来的。
这么玩意应用场景是什么?
其实在我们编程过程中就能使用到 栈 ,如何 函数调用栈 使用的就是栈结构
比如:执行函数。调用函数A,A又调用了B,B又调用了C。在执行 函数栈 的时候会先执行完C,C执行完后执行B,B执行完后执行A。等所有的函数执行完后,全部弹出栈后执行完毕,才能返回结果。所以 函数栈 就是使用了栈的内部机制实现的。
实现栈的api封装
基于
JavaScript实现栈的基本操作。
function Stack() {this.items = [];// push方法进栈Stack.prototype.push = function (el) {return this.items.push(el)}// pop方法出栈Stack.prototype.pop = function (el) {return this.items.pop();}// peek查看栈顶第一个元素Stack.prototype.peek = function () {return this.items[this.items.length - 1];}// isEmpty 查看栈是否为空Stack.prototype.isEmpty = function () {return this.items.length === 0;}// size 判断栈里面参数的长度Stack.prototype.size = function () {return this.items.length;}}let s = new Stack();s.push('a')s.push('b')s.push('c')s.push('d')console.log(s); // 应该显示abcd 但是显示了abc,是因为debugger走到的时候就会删掉,注释掉pop() 可以看到全部插入的数据。s.pop()console.log(s);console.log(s.peek());console.log(s.isEmpty());console.log(s.size());
封装十进制转二进制的函数
基于上面封装的函数,把十进制数组转为二进制函数。利用的就是栈的
先进后出原理。
//使用栈的方式,把十进制转为二进制function dec2bin(value) {// 基于上面封装的方法let stack = new Stack();// 传进的数组不小于0进继续执行while (value > 0) {// 取余得出进制stack.push(value % 2)// 得出整数下次循环value = Math.floor(value / 2)}let bin = '';// 判断栈里面的参数不为空就循环while (!stack.isEmpty())// 利用栈 先进后出的方式,拼接成字符串bin += stack.pop()return bin;}
