栈数据结构与算法Javascript描述(4)

栈 Stack


概念

栈是一种高效的数据结构,数据只能在栈顶添加或者删除,所以这样的操作很快,而且容易实现。栈的使用遍布程序语言的方方面面,从表达式求值到处理函数调用。

栈是一种特殊的列表,栈内的元素只能通过列表的一端访问,这一端称为栈顶。

对栈的操作

  • 将一个元素压入栈(入栈):push( )

  • 将一个元素弹出栈(出栈):pop( )

  • 预览栈顶的元素:peek( )

栈的实现

function Stack() {
    this.top = 0;
    this.dataStore = [];
    this.push = function(element){
        this.dataStore[this.top++] = element;
    };
    this.pop = function(){
        return this.dataStore[--this.top];
    }
    this.peek = function(){
        return this.dataStore[this.top-1];
    }
    this.clear = function(){
        this.top = 0;
    }
    this.length = function(){
        return this.top;
    }
}

使用Stack类

使用栈模拟递归过程(求n的阶乘)

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;
}

Tips:

仅以此文做个记录,纰漏之处万勿见笑~

原文地址:https://www.cnblogs.com/clover77/p/9187360.html