栈的出入js实现_用JS实现栈的结构

// 创建一个构造函数

function Stack() {

// 对象里的数值为空

this.items = []

// 数据进入栈

Stack.prototype.push = function (value) {

return this.items.push(value)

}

// 数据从栈取出

Stack.prototype.pop = function () {

return this.items.pop()

}

// 查看栈顶的元素 索引 -1

Stack.prototype.peek = function () {

return this.items[this.items.length - 1]

}

// 判断栈是否为空

Stack.prototype.empty = function () {

return this.items === 0

}

// 获取栈的大小

Stack.prototype.size = function (value) {

return this.items.length

}

// 栈中的元素转换成字符串

Stack.prototype.toString = function () {

var string = ''

for (let i = 0; i < this.items.length; i++) {

string += this.items[i] + ','

}

return string = string.substring(0, string.length - 1)

}

}

// 实例化对象

let s = new Stack()

s.push(1)

s.push(2)

s.push(3)

s.push(4)

s.push(5)

console.log(`将元素${s}压入栈`);

s.pop()

s.pop()

console.log(`取出了二个元素,还剩元素${s}在栈里`);

var a = s.peek()

console.log(`栈顶元素是${a}`);

var b = s.empty()

if (b === false) {

console.log('栈不是空的')

} else {

console.log('栈是空的');

}

var c = s.size()

console.log(`栈里有${c}个元素`);

var d = s.toString()

console.log(`栈中元素用字符串表示为:${d}`);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值