《剑指offer—面试题31:栈的压入、弹出序列》

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u011296723/article/details/81773602

《剑指offer—面试题31:栈的压入、弹出序列》
注明:仅个人学习笔记

import java.util.Stack;

public class IsPopOrder31
{
public static boolean IsPopOrder(int[] pushA, int[] popA)
{
if (pushA == null || popA == null)
{
return false;
}

    Stack<Integer> stack = new Stack<Integer>();

    // 如果当前栈空,将pushA中第一个元素压入
    if (stack.size() == 0)
    {
        stack.push(pushA[0]);
    }

    int nextPop = 0;
    int nextPush = 1;

    // 没将所有元素都做过出入栈的操作,不能退出;或者栈不为空,不能退出(因为有一种可能就是
    // ,第一个元素刚入栈,就出栈,然后栈空了,此时并未将左右元素都进行过出入栈的操作,所以不能只用栈是否为空作为循环结束条件)
    while (nextPush < pushA.length || stack.size() != 0)
    {
        if (stack.peek() == popA[nextPop])// 如果当前栈顶元素和出栈序列中的当前元素相等
        {
            stack.pop();// 出栈
            nextPop++;// 出栈序列后移一位
        } else
        {
            if (nextPush < pushA.length)// 入栈前检查index合法性
            {
                stack.push(pushA[nextPush]);// 如果当前栈顶元素和出栈序列中的当前元素不相等,那元素继续入栈
                nextPush++;
            } else
                return false;

        }
    }

    // if (j == pushA.length && i != popA.length)//这段就不需要了
    // {
    // return false;
    // }

    // 最后,如果两个数组均遍历完,说明出栈序列存在
    return true;

}

public static void main(String[] args)
{
    int[] pushA = { 1, 2, 3, 4, 5 };// 待入栈元素
    // int[] popA = { 4, 5, 3, 2, 1 };// 已知一个出栈序列
    int[] popA = { 4, 3, 5, 1, 2 };// 已知一个出栈序列,这个序列数不存在的,因为1比2先入栈,在出栈时不可能比2先出栈

    System.out.println(IsPopOrder(pushA, popA));
}

}

猜你喜欢

转载自blog.csdn.net/u011296723/article/details/81773602