栈的push、pop序列是否正确

题目:输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。为了简单起见,我们假设push序列的任意两个整数都是不相等的。

比如输入的push序列是12345,那么45321就有可能是一个pop系列。因为可以有如下的pushpop序列:push 1push 2push 3push 4poppush 5poppoppoppop,这样得到的pop序列就是45321。但序列43512就不可能是push序列12345pop序列。

分析:这到题除了考查对栈这一基本数据结构的理解,还能考查我们的分析能力。具体的实现代码如下:

// isStackPushPop.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <stack>

using namespace std;

bool isStackPushPop(int a[], int b[], int n)
{
 stack<int> ms;
 int i = -1, j = 0;
 while (i < n && j < n)
 {
  if (ms.empty() || ms.top() != b[j])
   ms.push(a[++i]);
  else
  {
   ms.pop();
   j ++;
  }
 }
 return ms.empty();
}

int main()
{
 int a[] = {1,2,3,4,5};
 int b[] = {5,4,2,3,1};
 //int b[]={4,5,3,2,1};
 //int b[]={5,4,3,2,1};
 cout<<isStackPushPop(a, b, 5)<<endl;
 system("pause");
 return 0;
}


 

// isStackPushPop.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"

#include <iostream>
#include <stack>

using namespace std;

bool isStackPushPop(int a[], int b[], int n)
{
	stack<int> ms;
	int i = -1, j = 0;
	while (i < n && j < n)
	{
		if (ms.empty() || ms.top() != b[j])
			ms.push(a[++i]);
		else
		{
			ms.pop();
			j ++;
		}
	} 
	return ms.empty();
}

int main()
{
	int a[] = {1,2,3,4,5};
	int b[] = {5,4,2,3,1};
	//int b[]={4,5,3,2,1};
	//int b[]={5,4,3,2,1};
	cout<<isStackPushPop(a, b, 5)<<endl;
	system("pause");
	return 0;
}



 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值