栈的压入、弹出序列

题目描述:给定两个序列,第一个是压栈的序列,判断第二个序列是不是出栈的序列。


思路:

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>


运行结果:




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值