栈的压入、弹出序列(面试题 22)

题目:输入两个整数序列,第一个序列表示站的压入顺序,请判断第二个栈是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。

#include "iostream"
#include "stack"
using namespace std;

void IsPopOrder(const int* pPush,const int* pPop)
{
	stack<int> stack1;
	const int* p1 =pPush;
	const int* p2 =pPop;
	stack1.push(*(p1++));
	while(*p1!=NULL&&!stack1.empty())
	{
		if (*p2 ==stack1.top())
		{
			stack1.pop();
			p2++;
		}
		else
		{
			stack1.push(*(p1++));
		}
	}
	if (!stack1.empty())
	{
		cout<<"第二个顺序不是一个出栈顺序!";
		return;
	}	
	if(*p1  ==NULL)
	{
		while(*p2 ==stack1.top())
		{
			stack1.pop();
			p2++;
		}
		if (*p2 !=NULL)
		{
				cout<<"第二个顺序不是一个出栈顺序!";
				return;
		}
	}
	cout<<"第二个是第一个的一个出栈顺序!\n";
}

void main()
{
	int input1[] ={1,2,3,4,5};
	int input2[] ={4,5,3,2,1};
	int input3[] ={4,3,5,1,2};
	IsPopOrder(input1,input2);
	IsPopOrder(input1,input3);
	cout<<endl;
}


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值