Javascript 基于数组的方式实现栈及其一系列相关的操作

Javascript 基于数组的方式实现栈及其一系列相关的操作

代码实现:

//封装栈类
function Stack() {
    this.items = []

    //栈的相关操作
    //1、将元素压入栈
    Stack.prototype.push = function (element) {
        this.items.push(element)
    }
    //2、将元素出栈
    Stack.prototype.pop = function () {
        return this.items.pop()
    }
    //3、查看栈顶元素
    Stack.prototype.peek = function () {
        return this.items[this.items.length - 1]
    }
    //4、判断栈是否为空
    Stack.prototype.isEmpty = function () {
        return this.items.length === 0
    }
    //5、回去栈中元素的个数
    Stack.prototype.size = function () {
        return this.items.length
    }
    //6、将栈中元素以字符串的方式返回
    Stack.prototype.toString = function () {
        let resultString = ''
        for (let i = 0 ; i < this.items.length ; i++) {
            resultString += this.items[i] + ' '
        }
        return resultString
    }
}

const s = new Stack()

s.push(12)
s.push(56)
s.push(100)
s.push(89)
s.push(789)
let a = s.pop()


console.log(a)
console.log(s.items)
console.log(s.peek())
console.log(s.size())
console.log(s.isEmpty())
console.log(s.toString())

结果如下:

789
[ 12, 56, 100, 89 ]
89
4
false
12 56 100 89

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值