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

题目:输入两个整数序列,第一个表示栈的压入顺序,青判断第二个序列是否为该栈的弹出序列。

代码示例:

#include<iostream>
#include<assert.h>
using namespace std;
#define MaxSize 100

class MyClass
{
	int data[MaxSize];
	int length;
public:
	MyClass()
	{
		length = -1;
	}
	~MyClass()
	{

	}
	bool empty(void);
	bool push(int n);
	bool pop(void);
	int gettop(void);
	bool IsPopSerial(int pushArr[],int popArr[], int n);
};
bool MyClass::empty(void)
{
	return (length == -1);
}
bool MyClass::push(int n)
{
	
	length++;
	if (length < MaxSize)
	{
		data[length] = n;
		return true;
	}
	else
		return false;
}
bool MyClass::pop(void)
{
	if (length >= 0)
	{
		length--;
		return true;
	}
	else
	{
		return false;
	}
}
int MyClass::gettop(void)
{
	assert(length >= 0);
	return data[length];
}
bool MyClass::IsPopSerial(int pushArr[], int popArr[], int n)
{
	if (pushArr == NULL || popArr==NULL||n <= 0)
		return false;

	for (int j = 0,i=0;j<=n&&i<=n;)
	{
		if (empty() || gettop()!=popArr[j])
		{
			push(pushArr[i]);
			i++;
		}
		int temp = gettop();
		if (temp == popArr[j])
		{
			pop();
			j++;
		}
	}
	if (empty())
		return true;
	else
		return false;
}
int main()
{
	MyClass mystack;
	const int n = 5;
	int pushArr[n] = { 5,3,4,2,7};
	int popArr[n] = { 4,5,3,2,7};
	bool flag = mystack.IsPopSerial(pushArr,popArr, n);
	if (flag)
	{
		for (int i = 0; i < n; i++)
			cout << popArr[i] << " ";
		cout << "是";
		for (int i = 0; i < n; i++)
			cout << pushArr[i] << " ";
		cout<<"的一个出栈序列!" << endl;
	}
	else
	{
		for (int i = 0; i < n; i++)
			cout << popArr[i] << " ";
		cout << "不是";
		for (int i = 0; i < n; i++)
			cout << pushArr[i] << " ";
		cout << "的一个出栈序列!" << endl;
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值