栈的实现:

class Stack {
  constructor() {
    this.store = [];
    this.top = 0;
  }

  push(item) {
    this.store[this.top++] = item;
    return this.store;
  }

  pop() {
    return this.store[--this.top];
  }

  peek() {
    return this.store[this.top - 1];
  }

  size() {
    return this.top;
  }

  claer() {
    this.store = [];
    this.top = 0;
  }
}

const stack = new Stack();

stack.push('shang');
stack.push('yy');
console.log(stack.push('big'));
console.log(stack.peek());
console.log(stack.size());

二、栈的应用

// 进制转换 10进制转换成其他进制

function dataconverse(data, base) {
  const stack = [];
  let num = data;
  do {
    stack.push(num % base);
    num = Math.floor(num / base);
  } while (num > 0);
  return stack.reduceRight((per, cur) => {
    return per + cur;
  }, '');
}
const result = dataconverse(125, 8);
console.log(result);

// 判断是回文
function isPalindrome(word) {
  const stack = [];
  for (let i = 0; i < word.length; i++) {
    stack.push(word[i]);
  }
  return stack.join('') === word;
}

console.log(isPalindrome('1001'));
function isPalindrome1(word) {
  return (
    word
      .split('')
      .reverse()
      .join('') === word
  );
}
console.log(isPalindrome1('110011'));

 

posted @ 2019-05-23 14:44  shangyueyue  阅读(106)  评论(0编辑  收藏  举报