栈
栈是遵循先进后出的方式,新元素和待删除的元素都放在栈的顶端。旧的元素都放在栈底
类似放书本一样,一摞书中我们一般都是从上(栈顶)放书或者从上面拿书
功能描述
- push 方法想栈堆中添加新元素
- pop删除元素
- peek查询栈顶的元素
- print 查询栈中每一个元素
- isEmpty判断栈是否尾空
- clear清空栈
代码实现
class Stack {
constructor() {
this._key = 0;
this._size = 0;
this._length = 0;
this._stackObj = {};
}
// 从栈尾删除 返回删除后的站栈
pop() {
if (this.isEmpty()) return [];
this._delete();
return this._stackObj;
}
//内置的删除的方法
_delete() {
const arr =Object.keys(this._stackObj);
const lastKey = arr.pop();
delete this._stackObj[lastKey];
this._key --;
this._length --;
}
_keys(){
return Object.keys(this._stackObj);
}
// 从后添加
push(value) {
this._stackObj[this._key] = value;
this._key++;
this._size++;
this._length++;
return this._stackObj;
}
isEmpty() {
return this._size === 0;
}
//清空
clear() {
this._size = 0;
this._key = 0;
this._stackObj = {};
}
toString() {
let str = '';
if (this.isEmpty()) return str;
this._keys.forEach(key => {
str = `${this._stackObj[key]}`
console.log(str);
});
}
// 查看栈顶的元素的值
peek() {
if (this.isEmpty())return;
return this._stackObj[this._keys().pop()];
}
print() {
if (this.isEmpty()) return null;
this._keys.forEach(key=>{
console.log(this._stackObj[key]
});
}
}
const s = new Stack();
s.push('xue');
s.push('name')
// console.dir(s.push('xie'));
console.log(s.peek());
console.log(s.pop());
console.log(s);