JavaScript算法学废宝典--前置技能一--栈

栈是一种特殊的列表,栈内的元素只能通过栈顶访问,栈被称为一种后入先出的数据结构。

栈的实现

function Stack() {
      this.dataStore = [];
      this.top = 0;
      this.push = push;
      this.pop = pop;
      this.peek = peek;
      this.clear = clear;
      this.length = length;
    }
    // 向栈内压入一个新元素
    function push(element) {
      this.dataStore[this.top++] = element;
    }
    // 返回栈顶元素
    function peek() {
      return this.dataStore[this.top - 1];
    }
    // 返回栈顶元素,同时变量top的值减1
    function pop() {
      return this.dataStore[--this.top];
    }
    // 清空一个栈
    function clear() {
      this.top = 0;
    }
    // 返回栈的长度
    function length() {
      return this.top;
    }

在这里插入图片描述

使用Stack类实际例子

将数字转换为二进制和八进制
//只针对2~9的情况
function mulBase(num, base) {
  var s = new Stack();
  do {
    s.push(num % base);
    num = Math.floor(num /= base);
  } while (num > 0) {
    var converted = "";
    while (s.length() > 0) {
      converted += s.pop();
    }
    return converted;
  }
}
// 测试
var num = 32;
var base = 2;
var newNum = mulBase(num, base);
console.log(num + " converted to base " + base + " is" + newNum);//32 converted to base 2 is100000

num = 125;
base = 8;
var newNum = mulBase(num, base);
console.log(num + " converted to base " + base + " is" + newNum);//125 converted to base 8 is175
判断字符串是否是回文
function isPalindrome(word) {
   var 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;
   }
 }
 // 测试
 var word = "hello";
 if (isPalindrome(word)) {
   console.log(word + " is a palindrome");
 } else {
   console.log(word + " is not a palindrome")
 }
 //hello is not a palindrome

 word = "racecar";
 if (isPalindrome(word)) {
   console.log(word + " is a palindrome");
 } else {
   console.log(word + " is not a palindrome")
 }
    //racecar is a palindrome
使用栈模拟递归过程

先用递归函数实现阶乘:

function factorial(n) {
  if (n === 0) {
    return 1;
  } else {
    return n * factorial(n-1)
  }
}

使用栈模拟:

// 使用栈模拟递归过程
 function fact(n) {
   var s = new Stack();
   while (n > 1) {
     s.push(n--);
   }
   var product = 1;
   while (s.length() > 0) {
     product *= s.pop();
   }
   return product;
 }
 //测试
 console.log(factorial(5));//120
 console.log(fact(5));//120
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值