程序员面试题精选100题(24)-栈的push、pop序列
题目:输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。为了简单起见,我们假设push序列的任意两个整数都是不相等的。
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。因为可以有如下的push和pop序列:push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,这样得到的pop序列就是4、5、3、2、1。但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。
其实这个题目就直接模拟push和pop的过程即可
有一个栈push_stack={1,2,3,4,5} , 一个栈pop_stack={4,5,3,2,1}
一个空栈 temp
int current = 0;List temp = new ArrayList();int top=0;boolean flag = true;for(int i =0;i<pop_stack.length;i++){ if(temp.size()>0) top = temp.get(temp.size()); if(current==push_stack.length-1 && top!=pop_stack[current]){ // 如果所有的数字都被push进栈仍然没有找到这个数字,表明该序列不可能是一个pop序列。 flag = false; } if(top==pop_stack[i]){ temp.remove(temp.size()); }else{//如果栈顶元素不是想要的,说明还没有push进来,现在push for(int j=current+1;j<push_stack.length;j++){ temp.add(push_stack[j]); if(push_stack[j]==top){ current=j; break; } } }}