對棧的操作: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 />");

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM