沿袭上个栈的内容,用数组实现了栈的数据结构的构建:

  1. class Stack {
  2. constructor(arr) {
  3. this.lists = arr
  4. }
  5. //压入栈
  6. push(list){
  7. this.lists.push(list)
  8. }
  9. // 取出栈顶元素
  10. pop(){
  11. return this.lists.pop()
  12. }
  13. // 查看栈顶元素
  14. peek(){
  15. return this.lists[this.lists.length -1]
  16. }
  17. // 判断栈是否为空
  18. isEmpty(){
  19. return this.lists.length === 0
  20. }
  21. // 获取栈中元素个数
  22. size(){
  23. return this.lists.length
  24. }
  25. //toString
  26. toString(){
  27. return this.lists.reduce(
  28. (a,b)=>
  29. a+ (a?'->':'') + (''+b)
  30. ,''
  31. )
  32. }
  33. }

用栈实现一个10进制转2进制的程序:

10进制转2进制的原理

  1. var num = 100
  2. num%2 0 num = Math.floor(num%2) //50
  3. num%2 0 num = Math.floor(num%2) //25
  4. num%2 1 num = Math.floor(num%2) //12
  5. num%2 0 num = Math.floor(num%2) //6
  6. num%2 0 num = Math.floor(num%2) //3
  7. num%2 1 num = Math.floor(num%2) //1
  8. num%2 1 num = Math.floor(num%2) //0
  9. 所有的余数从后往前拼接:1100100

用栈实现

  1. function dec2bin(num) {
  2. const s = new Stack([]);
  3. while (num > 0) {
  4. s.push(num % 2);
  5. num = Math.floor(num / 2);
  6. }
  7. let res = "";
  8. while (!s.isEmpty()) {
  9. res += s.pop();
  10. }
  11. return res;
  12. }
  13. console.log(dec2bin(100));
  14. console.log(dec2bin(1));
  15. console.log(dec2bin(2));
  16. console.log(dec2bin(10));