题目描述:给定两个序列,第一个是压栈的序列,判断第二个序列是不是出栈的序列。
思路:
1.模拟压栈、出栈操作。建立一个栈tem
2.将第一个序列中元素依次压入栈中,并将栈顶元素与第二个序列中元素进行比较,如果相同,则弹出,如果不同则压入;
3.直到第一个序列中元素全部压入栈中,检测栈是否为空,如果为空,说明第二个序列为出栈序列,反之不是。
代码如下:
<span style="font-size:14px;">#include<iostream>
#include<stack>
#include<vector>
using namespace std;
//实现代码
class Solution{
public:
bool isPopOrder(vector<int>tem1, vector<int>tem2){
if (tem1.size() == 0 || tem2.size() == 0)
return false;
stack<int>tem;
//模拟压栈、出栈操作
for (int i = 0,j=0; i < tem1.size(); i++){
tem.push(tem1[i]);
//将栈顶元素与出栈序列就行比较,如果相同,则出栈
while (!tem.empty() && tem.top() == tem2[j]){
tem.pop();
j++;
}
}
//如果栈为空,则说明是出栈序列,如果栈不为空,则说明不是出栈序列
return tem.empty();
}
};
//测试代码
int main(){
vector<int>tem1;
vector<int>tem2;
int a, b;
cout << "enter the push array: ";
while (cin >> a&&a){
tem1.push_back(a);
}
cout << "enter the pop array: ";
while (cin >> b&&b){
tem2.push_back(b);
}
Solution solution;
bool ans = solution.isPopOrder(tem1, tem2);
if (ans){
cout << "the ans is : yes" << endl;
}
else
cout << "the ans is : no" << endl;
system("pause");
return 0;
}</span>