javascript数据结构对于栈的封装

javascript数据结构对于栈的封装

function LIFO(){
    
    
    // 栈的相关属性
    this.items = []
    //栈的相关操作
    // 1.将元素压入到栈
    LIFO.prototype.push = function(element){
    
    
        this.items.push(element)
    }
    // 2.从栈中取出元素
    LIFO.prototype.pop = function(){
    
    
        return this.items.pop()
    }

    // 3。查看栈顶元素
    LIFO.prototype.peek = function(){
    
    
        return this.items[this.items.length - 1]
    }

    // 4.元素是否为空
    LIFO.prototype.isEmpty = function(){
    
    
        return this.items.length == 0
    }

    // 5.栈中元素的个数
    LIFO.prototype.size = function(){
    
    
        return this.items.length
    }

    // 6.toString方法
    LIFO.prototype.toString = function(){
    
    
        var resuletString = ''
        for (let i = 0; i < this.items.length; i++) {
    
    
            resuletString+=this.items[i]+" "
        }
        return resuletString
    }

}

//栈的使用
var lifo = new LIFO();

lifo.push(10)
lifo.push(20)
lifo.push(100)
console.log(lifo.toString());

猜你喜欢

转载自blog.csdn.net/weixin_45822938/article/details/123295290