总结自《学习JavaScript数据结构与算法第3版》
实现栈
一、定义栈
用数组来实现栈比较方便,有一些方法其实已经有了(pop啥的)。所以这边使用对象实现
export default class Stack {
constructor() {
this.count = 0;//记录位置
this.items = {};//存储数据的对象
}
push(element) {//往栈中加一个数据
this.items[this.count] = element;
this.count++;
}
pop() {//弹出一个数据
if (this.isEmpty()) {//如果数据是空的,直接就返回undefined
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;//count非0就说明有数据
}
size() {//获取栈长度
return this.count;
}
clear() {//清空栈
/* while (!this.isEmpty()) {
this.pop();
} */
this.items = {};//直接清空
this.count = 0;//直接归零
}
toString() {//读取整个栈
if (this.isEmpty()) {//判断非空
return '';//空栈嘛,直接返回‘’
}
let objString = `${this.items[0]}`;
for (let i = 1; i < this.count; i++) {
objString = `${objString},${this.items[i]}`;
}
return objString;
}
}