题目:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
思路:
- 创建一个栈用于压入弹出元素
- 遍历第一个序列,依次压入栈
- 第二个序列的首元素与栈顶元素相等则出栈
- 依次对比第二个序列的首元素与栈顶元素
- 栈为空时第二个序列就是栈的弹出顺序
代码:
package 栈的压入弹出序列;
import java.util.Stack;
/**
* 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。
* 假设压入栈的所有数字均不相等。
* 例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,
* 但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)
* @author Administrator
*/
public class Demo {
public boolean IsPopOrder(int[] pushA, int[] popA) {
// 输入参数不能为空
if (pushA == null || popA == null) {
return false;
}
// 创建一个栈来压入弹出元素
Stack<Integer> stack = new Stack<>();
int index = 0;
for (int i = 0; i < pushA.length; i++) {
// 压入第一个序列的元素
stack.push(pushA[i]);
// 第二个序列的首元素与栈顶元素相等则出栈
while (!stack.isEmpty() && stack.peek() == popA[index]) {
stack.pop();
// 第二个序列对应的元素弹出后向后移动一位
index++;
}
}
// 栈为空时第二个序列是栈的弹出顺序
return stack.empty();
}
public static void main(String[] args) {
Demo demo = new Demo();
int[] push = {1, 2, 3, 4, 5};
int[] pop1 = {4, 5, 3, 2, 1};
int[] pop2 = {3, 5, 4, 2, 1};
int[] pop3 = {4, 3, 5, 1, 2};
int[] pop4 = {3, 5, 4, 1, 2};
System.out.println("true: " + demo.IsPopOrder(push, pop1));
System.out.println("true: " + demo.IsPopOrder(push, pop2));
System.out.println("false: " + demo.IsPopOrder(push, pop3));
System.out.println("false: " + demo.IsPopOrder(push, pop4));
int[] push5 = {1};
int[] pop5 = {2};
System.out.println("false: " + demo.IsPopOrder(push5, pop5));
int[] push6 = {1};
int[] pop6 = {1};
System.out.println("true: " + demo.IsPopOrder(push6, pop6));
System.out.println("false: " + demo.IsPopOrder(null, null));
}
}