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到點,認...