栈的使用(stack)

1.栈的实现,使用数组

// @ts-check

export default class StackArray {

  constructor() {
    this.items = [];
  }
  push(element) {
    this.items.push(element);
  }

  pop() {
    return this.items.pop();
  }

  peek() {
    return this.items[this.items.length - 1];
  }

  isEmpty() {
    return this.items.length === 0;
  }

  size() {
    return this.items.length;
  }

  clear() {
    this.items = [];
  }

  toArray() {
    return this.items;
  }

  toString() {
    return this.items.toString();
  }
}

2.使用栈十进制转二进制

import Stack from "./stack-array.js";

// 十进制整数转二进制,使用栈的数据结构
/*******************************************************************************************************
* 比如 10转二进制整数
  1.  10/2= 5 余 0 
  2.  5/2= 2 余 1 
  3.  2/2= 1 余 0
  4.  1/2=0 余 1
  结果为1010;
*/

export const decimalToBinary = (num) => {
  const stack = new Stack();
  let binaryStr = "";

  while (num > 0) {
    // 余数
    const rem = num % 2;
    // 除数
    num = Math.floor(num / 2);
    stack.push(rem);
  }

  console.log("stack:", stack);
  //结果为:[ 0, 1, 0, 1 ]

  // 遍历整个栈,拼接每个元素
  while (!stack.isEmpty()) {
    binaryStr += stack.pop();
  }

  console.log("binaryStr:", binaryStr);
  //结果为:1010

};

decimalToBinary(10);
Contributors: masecho