zoukankan      html  css  js  c++  java
  • 对栈的操作: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 />");
  • 相关阅读:
    BZOJ3732: Network(Kruskal重构树)
    AtCoder Beginner Contest 103
    2018.7.21NOIP模拟赛?解题报告
    PE刷题记
    杜教筛入门
    浅谈积性函数的线性筛法
    BZOJ4916: 神犇和蒟蒻(杜教筛)
    BZOJ2818: Gcd(莫比乌斯反演)
    LD1-B(最短路径-SPFA)
    UVa 10837 A Research Problem 欧拉函数
  • 原文地址:https://www.cnblogs.com/feile/p/5372517.html
Copyright © 2011-2022 走看看