JS 栈

栈是一种高效的数据结构,因为对它的操作(添加/删除)都是在数据顶端操作
一种特殊的列表,对栈的操作只能在一端操作,这个地方叫栈顶

特点

  • 后入先出

操作方式

  • 入栈 push
  • 出栈 pop
  • 预览 peek

栈的抽象定义

  • 记录栈元素顶端的位置 top
  • 入栈方法 push
  • 出栈方法 pop
  • 预览 peek
  • 清除 clear
  • 元素个数 length

栈的实现 Stock

function Stock() {
    this.dataStore = [];
    this.top = 0;
    this.push=push;
    this.pop=pop;
    this.peek=peek;
    this.length=length;
    this.clear=clear;
    this.toString=toString;
}

// 入栈
// 1:添加元素 top +1
function push(item) {
    this.dataStore[this.top++]=(item);

}
// 出栈,返回栈顶元素,并且将元素的栈顶位置-1
// 1:删除元素 top--
function pop() {
    return this.dataStore[this.top--]
}
//预览顶端元素
function peek(){
    return this.dataStore[this.top-1];
}
//返回栈的长度
function length(){
    return this.top;
}
//清空栈
function clear(){
    this.top=0;
}

栈的常用例子 进制转换

//num要转换的数字 base 转换为几机制
function convertNum(num,base){
    var s=new Stock()
    while(num>0){
        console.log(num);
        s.push(num%base);
        num= Math.floor(num/=base);
    }
    var strResult="";
    while(s.length()>0){
        strResult+=s.pop();
    }
    return strResult;
}

例子:回文检查

//text 要检查的文字
function isImageText(text) {
    var words = text.toString().split('');
    var stock = new Stock();
    words.forEach(function (item) {
        stock.push(item.toString());
    })

    var result = "";
    while (stock.length() > 0) {
        result += stock.pop().toString();
    }
    console.log(result);
    if (result == text) {
        return true;
    } else {
        return false;
    }
}

例子递归

// 计算阶层

function fat(n) {
    var stock = new Stock();
    while (n > 0) {
        stock.push(n);
        n--;
    }
    var result = 1;
    while (stock.length() > 0) {
        result *= stock.pop()
    }
    return result;
}
原文地址:https://www.cnblogs.com/dark-liu/p/5789829.html