栈的压入、弹出序列
题目
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。
假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是
该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这
两个序列的长度是相等的)
思路
首先肯定是要一个help栈的,然后将一个个分别按照入栈顺序 入栈 当出栈顺序的值和入栈top相等时候则 出栈。
代码
public class IsPopOrder {
public boolean IsPopOrder(int [] push,int [] pop) {
if(push==null||pop==null){
return false;
}
Stack<Integer> help = new Stack<>();//帮助栈
int pushIndex = 0;
int popIndex = 0;
while (popIndex<push.length){
while (pushIndex<push.length&&(help.isEmpty()||help.peek()!=pop[popIndex])){
help.push(push[pushIndex]);
pushIndex++;//依次不等的情况下入栈
}
if (help.peek()==pop[popIndex]){//当stack的top和pop相同的时候stackpop出来。
help.pop();
popIndex++;
}else {
return false;
}
}
return true;
}
}