介绍

栈(stack)结构 是一种受限制的数据结构,它只能在一端添加和删除,先进的后出,后进的先出。就好比羽毛球筒,先进去的永远是最后一个出来的。

栈 - 图1

这么玩意应用场景是什么?

其实在我们编程过程中就能使用到 ,如何 函数调用栈 使用的就是栈结构
比如:执行函数。调用函数A,A又调用了B,B又调用了C。在执行 函数栈 的时候会先执行完C,C执行完后执行B,B执行完后执行A。等所有的函数执行完后,全部弹出栈后执行完毕,才能返回结果。所以 函数栈 就是使用了栈的内部机制实现的。

实现栈的api封装

基于 JavaScript 实现栈的基本操作。

  1. function Stack() {
  2. this.items = [];
  3. // push方法进栈
  4. Stack.prototype.push = function (el) {
  5. return this.items.push(el)
  6. }
  7. // pop方法出栈
  8. Stack.prototype.pop = function (el) {
  9. return this.items.pop();
  10. }
  11. // peek查看栈顶第一个元素
  12. Stack.prototype.peek = function () {
  13. return this.items[this.items.length - 1];
  14. }
  15. // isEmpty 查看栈是否为空
  16. Stack.prototype.isEmpty = function () {
  17. return this.items.length === 0;
  18. }
  19. // size 判断栈里面参数的长度
  20. Stack.prototype.size = function () {
  21. return this.items.length;
  22. }
  23. }
  24. let s = new Stack();
  25. s.push('a')
  26. s.push('b')
  27. s.push('c')
  28. s.push('d')
  29. console.log(s); // 应该显示abcd 但是显示了abc,是因为debugger走到的时候就会删掉,注释掉pop() 可以看到全部插入的数据。
  30. s.pop()
  31. console.log(s);
  32. console.log(s.peek());
  33. console.log(s.isEmpty());
  34. console.log(s.size());

封装十进制转二进制的函数

基于上面封装的函数,把十进制数组转为二进制函数。利用的就是栈的 先进后出 原理。

  1. //使用栈的方式,把十进制转为二进制
  2. function dec2bin(value) {
  3. // 基于上面封装的方法
  4. let stack = new Stack();
  5. // 传进的数组不小于0进继续执行
  6. while (value > 0) {
  7. // 取余得出进制
  8. stack.push(value % 2)
  9. // 得出整数下次循环
  10. value = Math.floor(value / 2)
  11. }
  12. let bin = '';
  13. // 判断栈里面的参数不为空就循环
  14. while (!stack.isEmpty())
  15. // 利用栈 先进后出的方式,拼接成字符串
  16. bin += stack.pop()
  17. return bin;
  18. }