如何在JavaScript中实现栈(Stack)和队列(Queue)?
我想要使用逆波兰表达式算法,因此需要这些数据结构。
如何在JavaScript中实现栈(Stack)和队列(Queue)?
我想要使用逆波兰表达式算法,因此需要这些数据结构。
你可以在ES6类中使用WeakMaps来实现私有属性,并且JavaScript语言中的String属性和方法具有以下优点:
const _items = new WeakMap();
class Stack {
constructor() {
_items.set(this, []);
}
push(obj) {
_items.get(this).push(obj);
}
pop() {
const L = _items.get(this).length;
if(L===0)
throw new Error('Stack is empty');
return _items.get(this).pop();
}
peek() {
const items = _items.get(this);
if(items.length === 0)
throw new Error ('Stack is empty');
return items[items.length-1];
}
get count() {
return _items.get(this).length;
}
}
const stack = new Stack();
//now in console:
//stack.push('a')
//stack.push(1)
//stack.count => 2
//stack.peek() => 1
//stack.pop() => 1
//stack.pop() => "a"
//stack.count => 0
//stack.pop() => Error Stack is empty