您的位置:首页 > Web前端

剑指Offer_21_栈的压入、弹出序列

2016-08-16 09:54 225 查看

题目描述

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

解题思路

遍历两个数组,首先判断入栈元素是否和出栈队列当前元素相同,如果相同,则两个数组都指向下一个元素,如果不相等,则将第一个数组的元素入栈。每次第二个数组中的元素需要和栈顶元素以及第一个数组元素比较。如果最后遍历完成两个数组且栈为空,则说明是出栈顺序。

实现

import java.util.LinkedList;

public class Solution {
public boolean IsPopOrder(int [] pushA,int [] popA) {
if (popA == null && pushA == null) return true;
else if (popA == null || pushA == null) return false;
else if (popA.length != pushA.length) return false;
LinkedList<Integer> stack = new LinkedList<>();
int pIndex = 0, popIndex = 0;
while (pIndex < pushA.length){
if (!stack.isEmpty()){
int in = stack.peek();
if (popA[popIndex] == in){
stack.pop();
popIndex++;
continue;
}
}
stack.push(pushA[pIndex++]);
}
while (!stack.isEmpty() && popA[popIndex] == stack.peek()){
stack.pop();
popIndex ++;
}
if (!stack.isEmpty() || popIndex != popA.length) return false;
return true;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  出栈 入栈 Java