更详尽参看:
4️⃣ 栈
利用数组实现
class StackArray {
constructor() {
this.items = []
}
push(elem) {
this.items.push(elem)
}
pop() {
if (this.isEmpty()) {
return undefined
}
return this.items.pop()
}
isEmpty() {
return this.items.length === 0
}
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[this.items.length - 1]
}
size() {
return this.items.length
}
clear() {
this.items = []
}
toString() {
let objString = ''
return this.items.reduce((prev,cur,index)=> {
if (index === this.items.length - 1) {
return prev+cur
}
return prev+cur+','
},'')
}
}
let s = new StackArray()
s.push(1)
s.push(2)
s.push('1111')
console.log(s)
console.log(s.toString())
s.pop()
console.log(s.size())
console.log(s.peek())
s.clear()
console.log(s)
console.log(s.size())
console.log(s.peek())
// 输出
// StackArray { items: [ 1, 2, '1111' ] }
// 1,2,1111
// 2
// 2
// StackArray { items: [] }
// 0
// undefined
利用对象实现
class Stack {
constructor() {
this.count = 0
this.items = {}
}
push(elem) {
this.items[this.count] = elem
this.count++
}
pop() {
if (this.isEmpty()) {
return undefined
}
this.count--
const result = this.items[this.count]
delete this.items[this.count]
return result
}
peek() {
if (this.isEmpty()) {
return undefined
}
return this.items[this.count - 1]
}
isEmpty() {
return this.count === 0
}
size() {
return this.count
}
clear() {
this.items = {}
this.count = 0
}
toString() {
if (this.isEmpty()) {
return ''
}
let objString = `${this.items[0]}`
for(let i=1;i<this.count;i++){
objString += `,${this.items[i]}`
}
return objString
}
}
let s = new Stack()
s.push(1)
s.push(2)
s.push('1111')
console.log(s)
console.log(s.toString())
s.pop()
console.log(s.size())
console.log(s.peek())
s.clear()
console.log(s)
console.log(s.size())
console.log(s.peek())
// 输出
// Stack { count: 3, items: { '0': 1, '1': 2, '2': '1111' } }
// 1,2,1111
// 2
// 2
// Stack { count: 0, items: {} }
// 0
// undefined