题解 | #栈的压入、弹出序列#
栈的压入、弹出序列
http://www.nowcoder.com/practice/d77d11405cc7470d82554cb392585106
class Stack {
constructor(){
this.item = []
}
push(i){
this.item.push(i)
}
pop(){
this.item.pop()
}
top(){
return this.item[this.item.length - 1 ]
}
isEmpty(){
return this.item.length === 0
}
}
function IsPopOrder(pushV, popV)
{
// write code here
if(!pushV.length){
return true
}
let stack = new Stack()
let p = 0 //目前入栈到的下标
stack.push(pushV[p]) //初始化入栈1个
for(let i = 0; i < popV.length; i++){
while(stack.top() !== popV[i] ){ //继续入栈
if(p === pushV.length - 1){ //已经全部入栈 无法入栈
return false
}
stack.push(pushV[++p])
}
if(!stack.isEmpty() && stack.top() === popV[i] ){ //出栈
stack.pop()
}
}
return true
}
module.exports = {
IsPopOrder : IsPopOrder
};