【剑指offer】面试题31:栈的压入,弹出序列
輸入兩個整數序列,第一個序列表示棧的壓入順序,請判斷第二個序列是否可能為該棧的彈出順序。假設壓入棧的所有數字均不相等。例如序列1,2,3,4,5是某棧的壓入順序,序列4,5,3,2,1是該壓棧序列對應的一個彈出序列,但4,3,5,1,2就不可能是該壓棧序列的彈出序列。(注意:這兩個序列的長度是相等的)
代碼:
package offer;
import java.util.Stack;
public class ti31 {
?? ?static boolean IsPopOrder(int push[],int pop[])
?? ?{
?? ??? ?Stack<Integer> stack = new Stack<Integer>();
?? ??? ?int x = 0;
?? ??? ?int i = 0;
?? ??? ?while(x<=pop.length-1)
?? ??? ?{
?? ??? ??? ?if(stack.empty()&&i<push.length)
?? ??? ??? ?{
?? ??? ??? ??? ?stack.add(push[i]);
?? ??? ??? ??? ?i++;
?? ??? ??? ?}
?? ??? ??? ?while(!stack.empty()&&pop[x]==stack.peek())
?? ??? ??? ?{
?? ??? ??? ??? ?stack.pop();
?? ??? ??? ??? ?x++;
?? ??? ??? ?}
?? ??? ??? ?if(!stack.empty()&&pop[x]!=stack.peek())
?? ??? ??? ?{
?? ??? ??? ??? ?if(i<push.length)
?? ??? ??? ??? ?{
?? ??? ??? ??? ??? ?stack.add(push[i]);
?? ??? ??? ??? ??? ?i++;
?? ??? ??? ??? ?}
?? ??? ??? ??? ?else
?? ??? ??? ??? ?{
?? ??? ??? ??? ??? ?return false;
?? ??? ??? ??? ?}
?? ??? ??? ?}
?? ??? ?}
?? ??? ?return true;
?? ?}
?? ?public static void main(String[] args)
?? ?{
?? ??? ?int push[] = {1,2,3,4,5};
?? ??? ?int pop[] = {4,5,3,2,1};
?? ??? ?System.out.println(IsPopOrder(push,pop));
?? ?}
}
?
總結
以上是生活随笔為你收集整理的【剑指offer】面试题31:栈的压入,弹出序列的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Mybatis中example的使用
- 下一篇: Leetcode--120. 三角形最小