栈的实现
实现栈 具有以下功能
- push : 添加一个(或几个)新元素到栈顶
- pop : 移除栈顶的元素,同时返回被移除的元素
- peek : 返回栈顶元素,不对栈做任何修改
- isEmpty : 如果栈里没有任何元素返回 true,否则返回 false
- clear : 清空栈中元素
- size: 返回栈中元素个数
- print : 把栈中存放的元素打印出来
ES5 实现方式
function Stack(){ let items=[] this.push=function(item){ items.push(item) } this.pop=function () { return items.pop() } this.peek=function () { return items[items.length-1] } this.clear=function(){ items=[] } this.print=function () { console.log(items.toString()) } this.size=function(){ return items.length() } this.isEmpty=function(){ return items.length==0 } }
ES6 实现
class Stack{ constructor(){ this.items=[] } push(item){ this.items.push(item) } pop(){ return this.items.pop() } peek(){ let length=this.items.length return this.items[length-1] } isEmpty(){ return this.items.length==0 } clear(){ this.items=[] } size(){ return this.items.length } print(){ console.log(this.items.toString()) } }
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

上一篇: 队列实现
下一篇: 谈谈自己对于 AOP 的了解
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论