可以使用数组模拟栈的操作,主要要熟悉判断压入和弹出的判断方法
function IsPopOrder(pushV, popV)
{
let stack = new Stack();
let popNum=0;
for(let i=0;i<pushV.length;i++){
stack.push(pushV[i]);
//while 不断对比栈顶元素,检查了 pushA压栈过程中出栈的情况。
while(!stack.isEmpty()&&stack.peek()==popV[popNum]){
stack.pop();
popNum++;
}
}
return stack.isEmpty();
}
class Stack {
constructor() {
this.item = [];
}
push = function (element) {
this.item.push(element)
}
pop = function () {
return this.item.pop();
}
peek = function () {
return this.item[this.item.length - 1];
}
isEmpty = function () {
return this.item.length === 0;
}
toString = function () {
let res = '';
this.item.forEach( item => {
res += item + ''
})
return res;
}
}
module.exports = {
IsPopOrder : IsPopOrder
};