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
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();
}
};