数据结构--判断是否出栈

2022-07-27,

一、给出一个栈的入栈顺序,判断一个出栈顺序是否正确:

思路:使用栈stack和数组(队列)实现,首先将需要出栈的顺序放入数组data(或者将出栈顺序放入队列queue),然后按照入栈顺序入栈,入栈后判断栈顶的元素是否等于数组的第一个索引值,即data[0]的值(如果是队列则判断是否等于队列的head元素),如果相等,则将次元素弹出,数组索引+1,(queue队列弹出head元素),然后继续判断。如果不相等,则继续按照顺序往stack中push元素:

class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        int len = pushed.length;
        int count =0;
        Stack<Integer> stack = new Stack<Integer>();
        for(int i=0;i<len;i++){
            stack.push(pushed[i]);
            while(!stack.isEmpty()&&stack.peek() == popped[count]){
                stack.pop();
                count++;
            }
        }
        return stack.isEmpty();
    }
}

本文地址:https://blog.csdn.net/qq_42284554/article/details/110232806

《数据结构--判断是否出栈.doc》

下载本文的Word格式文档,以方便收藏与打印。