Stack With Array
class StackArr {
constructor() {
this.items = [];
}
push(el) {
this.items.push(el)
}
pop() {
this.items.pop()
}
top() {
return this.items[this.items.length - 1]
}
isEmpty() {
return this.items.length == 0
}
size() {
return this.items.length
}
toString() {
return this.items.join('-')
}
clear() {
this.items = []
}
}
Stack With Object
class Stack {
constructor() {
this.count = 0
this.items = {}
}
push(el) {
// 以count为key
this.items[this.count] = el
this.count++
}
pop() {
if (!this.count) {
return undefined
}
this.count--
let res = this.items[this.count]
delete this.items[this.count]
return res
}
peek() {
if (!this.count) {
return undefined
}
return this.items[this.count - 1]
}
isEmpty() {
return this.count == 0
}
size() {
return this.count
}
toString() {
if (!this.count) {
return ''
}
// let str = `${this.items[0]}`;
// for (let i = 1; i < this.count; i++) {
// str = `${str},${this.items[i]}`;
// }
let str = this.items[0]
for (let index = 1; index < this.count; index++) {
str += ',' + this.items[index]
}
return str;
}
clear() {
this.items = {}
this.count = 0
}
}