class Stack {
constructor() {
this.item={}
this.count=0
}
//栈顶添加
push(item){
this.item[this.count]=item
this.count++
}
//删除
pop(){
if(this.isEmpty()){
return undefined
}
this.count--
const result = this.item[this.count]
delete this.item[this.count]
return result
}
//查看栈顶元素
peek() {
if(this.isEmpty()){
return undefined
}
return this.item[this.count]
}
//清空栈
clear() {
this.item = {}
this.count=0
}
//栈是否为空
isEmpty() {
return this.count===0
}
//查看栈长度
size(){
return this.count
}
//创建toString方法
toString() {
if (this.isEmpty()) {
return ``
}
let str = `${this.item[0]}`
for (let i =1;i < this.count; i++){
str+=`,${this.item[i]}`
}
return str
}
}
JavaScript不用数组实现栈的方式
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
推荐阅读更多精彩内容
- 1.使用ES6的Set进行去重 使用此方法非常简单,通俗易懂。该方法主要利用了Set内部结构的原理,然后通过Arr...
- 题目描述 定义栈的数据结构,请在该类型中实现一个能够得到栈最小元素的min函数。 在读题时,最开始没get到点,认...