对栈的操作:push()&pop()方法

栈被称为一种后进先出( LIFO, last-in-first-out) 的数据结构

tips:pop()&peek()的区别:

  pop() 方法可以访问栈顶的元素, 调用后, 栈顶元素从栈中被永久性地删除。

  peek() 方法则只返回栈顶元素, 而不删除它。

    function Stack() {
        this.dataStore = [];
        this.top = 0;//top的值等同于数组内的元素个数
        
        this.push = push;
        
        this.pop = pop;
        this.peek = peek;
        this.clear = clear;
        this.length = length;
    }
    function push(element) {
        this.dataStore[this.top++] = element;
    }

    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;
    }
    var s = new Stack();
    s.push("David");
    s.push("Raymond");
    s.push("Bryan");
    document.write("length: " + s.length() + "<br />");
    //document.write("length: " + s.top + "<br />");//与上述结果相同
    document.write(s.peek() + "<br />");//peek() 方法则只返回栈顶元素, 而不删除它。
    var popped = s.pop();
    document.write("The popped element is: " + popped + "<br />");
    s.clear();
    document.write("length: " + s.length() + "<br />");
    document.write(s.peek() + "<br />");
原文地址:https://www.cnblogs.com/feile/p/5372517.html