這里我用下面的例子子來講解一下模擬棧的實(shí)現(xiàn)。
例子1:pushed = [1,2,3,4,5] popped = [4,5,3,2,1]
思路:第一步:我們先創(chuàng)建一個(gè)棧,然后將pushed的數(shù)據(jù)壓進(jìn)去
第二步:判斷! 當(dāng)壓入棧的數(shù)據(jù)和popped第一個(gè)數(shù)據(jù)一樣的時(shí)候,我們就出數(shù)據(jù)。ps:這時(shí)可以用一個(gè)posi來記錄要比較的數(shù)據(jù)
第三步:最后判斷棧是否為空,為空就true,否則則false文章來源:http://www.zghlxwxcb.cn/news/detail-687946.html
下面是源碼:文章來源地址http://www.zghlxwxcb.cn/news/detail-687946.html
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();
}
};
到了這里,關(guān)于LeetCode——棧的壓入、彈出序列的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!