阅读《数据结构与算法 JavaScript 描述 第二版》之栈

921 阅读1分钟

对栈的操作

Last-in-first-out (LIFO)中文描述 后进先出。有时候数据只能从栈顶 添加/删除,特点就是操作很很快。

栈顶

基于栈顶的操作。

入栈出栈

  • push 入栈
  • pop 出栈

栈的实现

function Stack() {
  this.dataStore = [];
  this.top = 0;
}

Stack.prototype.push = function (element) {
  this.dataStore[this.top++] = element;
};

Stack.prototype.pop = function () {
  return this.dataStore[--this.top];
};

Stack.prototype.peek = function () {
  return this.dataStore[this.top - 1];
};

Stack.prototype.length = function () {
  return this.top;
};

Stack.prototype.clear = function () {
  this.top = 0;
};

使用 Stack 类

进制之间的相互转化

function mulBase(num, base) {
  let s = new Stack();

  do {
    s.push(num % base);
    num = Math.floor(num /= base);
  } while (num > 0);

  let converted = "";
  while (s.length() > 0) {
    converted += s.pop();
  }

  return converted;
}

// 转换: 二进制
let num = 32;
let base = 2;
let newNum = mulBase(num, base);
console.log(`${num} converted to base ${base} is ${newNum}`)

// 转换:八进制
let num1 = 125;
let base1 = 8;
let newNum1 = mulBase(num1, base1);
console.log(`${num1} converted to base ${base}1 is ${newNum1}`)

判断回文字符串

function isPalindrome(word) {
  let s = new Stack();
  for (var i = 0; i < word.length; ++i) {
    s.push(word[i]);
  }

  var rword = '';
  while (s.length() > 0) {
    rword += s.pop();
  }

  if (word == rword) {
    return true
  } else {
    return false
  }
}

let word = "hello";

if(isPalindrome(word)) {
  console.log(`${word} is a palindrome.`);
} else {
  console.log(`${word} is not a palindrome`);
}

word = 'raecar'

if(isPalindrome(word)) {
  console.log(`${word} is a palindrome.`)
} else {
  console.log(`${word} is not a palindrome.`)
}

小结

  • 栈顶
  • 栈的 api