/**
* 栈的压入,弹出序列
*
* 因为有入栈序列,所以从入栈开始,遍历入栈序列
* 1. 遍历入栈序列时,每遍历一个,就判断是否是出栈序列中的需要弹出的值,
* 2. 如果是则弹出,然后出栈序列加一,接着继续根据入栈序列添加(for循环继续)
* 3. 如果不是,则继续根据入栈序列添加,直到匹配出栈序列需要的数字为止
* 4. 如果遍历完都发现没有匹配的,则该出栈序列不是合法出栈序列
*/
public static boolean isPopValid(int[] pushOrder, int[] popOrder) {
if (pushOrder.length == 0 || popOrder.length == 0 || pushOrder.length != popOrder.length)
return false;
Stack<Integer> stack = new Stack<>();
int j = 0;
for (int current : pushOrder) {
stack.push(current);
while ((!stack.empty()) && (stack.peek() == popOrder[j])) {
stack.pop();
j++;
}
}
if (stack.empty()) {
return true;
} else {
return false;
}
}
public static void main(String[] args) {
Stack<Integer> stack = new Stack<>();
stack.push(1);
stack.push(2);
stack.push(3);
stack.push(4);
stack.push(5);
int push[] = {1, 2, 3, 4, 5};
int pop[] = {4, 5, 3, 2, 1};
boolean is = isPopValid(push, pop);
System.out.println("is valid : " + is);
}
栈的压入 弹出序列-Java
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。
推荐阅读更多精彩内容
- 栈的压入、弹出序列 题目描述 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。...