剑指offer面试题22:栈的压入、弹出序列
题目描述:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
function Stack() {
var items = [];
this.push = function(element) {
items.push(element);
}
this.pop = function() {
items.pop();
}
this.isEmpty = function() {
return items.length === 0;
}
this.peek = function() {
return items[items.length-1];
}
this.isPopOrder = function(pushArr, popArr) {
var isPossible = false,
len = pushArr.length;
if(pushArr !== '' && popArr !== '') {
var i = 0,
j = 0;
while(j < len) {
while(this.peek() !== popArr[j]) {
if(i >= len) {
return isPossible;
}
this.push(pushArr[i]);
i++;
}
if(this.peek() !== popArr[j]) {
return isPossible;
}
this.pop();
j++;
}
if(this.isEmpty() && j == len){
isPossible = true;
}
return isPossible;
}
}
}
var stack = new Stack();
console.log(stack.isPopOrder([1,2,3,4,5],[5,4,3,2,1]));