stack-array
栈
一、创建一个基于Javascript对象的Stack类
class Stack {
constructor () {
this.count = 0
this.items = {}
}
}
2.向栈中插入元素
push (elements) {
this.items[this.count] = elements
this.count++
return elements
}
3.验证一个栈是否为空
isEmpty () {
return this.items.length === 0
}
4.获取栈的大小
size () {
return this.items.length
}
5.从栈中弹出元素
pop () {
if (this.isEmpty()) {
return undefined
}
this.count--
const result = this.items[this.count]
delete this.items[this.count]
return result
}
6.查看栈顶元素
peek () {
if (this.isEmpty()) {
return undefined
}
return this.items[this.count - 1]
}
7.清空栈
clear () {
this.items = {}
this.count = 0
// while (!this.isEmpty()) {
// this.pop()
// }
}
8.创建toString方法
toString () {
if (this.isEmpty()) {
return ''
}
let str = ''
for (let i = 0; i < this.count; i++) {
str += `${this.items[i]}`
}
return str
}
二、创建一个基于Javascript数组的Stack类
class Stack {
constructor() {
this.stack = []
}
size() {
return this.stack.length
}
push() {
const args = [].slice.call(arguments)
this.stack = [...this.stack, ...args]
return this.stack.length
}
pop() {
return this.stack.splice(this.size() - 1, 1)[0]
}
peek() {
return this.stack[this.size() - 1]
}
isEmpty() {
return this.size() === 0
}
}