牛客原题链接:栈的压入、弹出序列
题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
代码实现:
import java.util.Stack;
public class Stack_practice {
public static void main(String[] args) {
test3();//栈的压入弹出顺序
}
private static void test3() {
Solution solution = new Solution();
int [] a = new int[]{1,2,3,4,5};
int [] b = new int[]{4,5,3,2,1};
int [] c = new int[] {4,3,5,1,2};
System.out.println(solution.IsPopOrder(a,b));
System.out.println(solution.IsPopOrder(a,c));
}
}
class Solution {
public boolean IsPopOrder(int[] pushA, int[] popA) {
Stack<Integer> stackPush = new Stack<>();
Stack<Integer> stackPop = new Stack<>();
//先将输出数组保存到栈stackPop中
for (int i : popA) {
stackPop.push(i);
}
//然后将输入数组放到stackPush栈中,如果遇到和输出栈栈顶元素相同的值时,同时出栈
for (int i : pushA) {
stackPush.push(i);
if (stackPop.peek() == i) {
stackPush.pop();
stackPop.pop();
}
}
//如果最后两个栈相同的话即为可以实现入栈出栈序列要求
if (stackPush.equals(stackPop)) {
return true;
} else {
return false;
}
}
}