JavaScript-實現數據結構-棧

棧,後進先出,受限制的線性表。
只容許在一端進行添加和刪除操做。this

如下代碼是棧的封裝及使用:prototype

<script>
    //封裝棧類
    function Stack(){
        //棧中的屬性
        this.items = [];
        //棧的相關操做
        //一、將元素壓入棧
        Stack.prototype.push = function(element){
            this.items.push(element);
        }
        //二、從棧中取出棧頂元素
        Stack.prototype.pop = function(){
            return this.items.pop();
        }
        //三、查看棧頂元素
        Stack.prototype.peek = function(){
            return this.items[this.items.length-1];
        }
        //四、判斷棧是否爲空
        Stack.prototype.isEmpty = function(){
            return this.items.length == 0;
        }
        //五、獲取棧中元素的個數
        Stack.prototype.size = function(){
            return this.items.length;
        }
        //六、toString方法
        Stack.prototype.toString = function(){
            var resultString = '';
            for(var i=0;i<this.items.length;i++){
                resultString += this.items[i] + '';
            }
            return resultString;
        }
    }
    
    //棧的使用
    var s = new Stack();
    s.push(20);
    s.push(12);
    s.push(100);
    
    s.pop();
    s.pop();
    alert(s);
    
    alert(s.peek());
    alert(s.isEmpty());
    alert(s.size());
</script>
相關文章
相關標籤/搜索