栈的压入弹出序列问题

#define _CRT_SECURE_NO_WARNINGS 1 #include<stdlib.h> #include<iostream> using namespace std; #include<vector> #include<stack> /* 题目要求: 输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。 假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序, 序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。 (注意:这两个序列的长度是相等的) */ /* 解题思路: 利用一个栈,将pushV中的元素依次插入,若栈顶元素和popV中pos元素相等则pop栈顶元素并让pos指向下一个元素 pushV中元素插入结束若栈为空则说明满足条件,否则不满足。 */ class Solution { public: bool IsPopOrder(vector<int> pushV, vector<int> popV) { stack<int> s; if (pushV.size() != popV.size()) { return false; } int i = 0; int j = 0; while (i < pushV.size()) { s.push(pushV[i++]); while (!s.empty() && s.top() == popV[j]) { s.pop(); j++; } } if (s.empty()) { return true; } else { return false; } } }; int main() { vector<int>v1{1, 2, 3, 4, 5}; vector<int>v2{ 4,5,3,2,1}; Solution s; int a=s.IsPopOrder(v1, v2); cout << a << endl; system("pause"); return 0; }
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章