LeetCode - stack push, pop sequence

insert image description here
Here I use the following example to explain the implementation of the simulation stack .
Example 1: pushed = [1,2,3,4,5] popped = [4,5,3,2,1]
Idea: Step 1: We first create a stack, and then push the pushed data into it

Step Two: Judge! When the data pushed onto the stack is the same as the first data popped, we will output the data. ps: At this time, a posi can be used to record the data to be compared

Step 3: Finally, judge whether the stack is empty, true if it is empty, otherwise false

insert image description here
insert image description here
insert image description here
Here is the source code:

class Solution {
    
    
public:
    bool validateStackSequences(vector<int>& pushed, vector<int>& popped) {
    
    
        stack<int> st;
        int posi = 0;
        for(auto pushval : pushed)
        {
    
    
            st.push(pushval);

            while(!st.empty() && st.top() == popped[posi])
            {
    
    
                st.pop();
                ++posi;
            }
        }
        
        return st.empty();
    }
}; 

Guess you like

Origin blog.csdn.net/m0_72165281/article/details/132614039