栈的压入、弹出序列

/************************************************************
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二
个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如
序列1,2,3,4,5为某栈的压入顺序,则4,5,3,2,1是该栈对应的一个弹出
序列;而4,3,5,1,2,就不不可能是对应的弹出序列。
************************************************************/

#include<stdio.h>
#include<stack>

using namespace std;
/*
bool stackPushPopOrder(int* pushOrder, int* popOrder,int length)
{
	if(!pushOrder || !popOrder || length<=0)
		return false;

	stack<int> intStack;

	intStack.push(pushOrder[0]);
	bool result = false;
	
	int index = 1;
	int i;
	for(i=0; i<length; ++i)
	{
		for(int j = index; j<=length; ++j)
		{
			if(intStack.top() != popOrder[i] || intStack.empty())
			{
				if(j == 5)	//如果所有数字都压入栈,仍没有找到相应弹出数字
					return false;

				intStack.push(pushOrder[j]);
				++index;
			}
			else
			{
				intStack.pop();
				break;
			}
		}
	}

	if(intStack.empty() && index==length && i==length)
		return true;
	else
		return false;	

}
*/

//对比一下书上的参考答案
bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
{
	bool bPossible = false;
	if(pPush != NULL && pPop != NULL && nLength>0)
	{
		const int* pNextPush = pPush;
		const int* pNextPop = pPop;

		stack<int>	stackData;
		while(pNextPop - pPop < nLength)
		{
			while(stackData.empty() || stackData.top() != *pNextPop)
			{
				if(pNextPush - pPush == nLength)
					break;

				stackData.push(*pNextPush);
				++pNextPush;
			}

			if(stackData.top() != *pNextPop)
				break;

			stackData.pop();
			++pNextPop;
		}
		if(stackData.empty() && pNextPop - pPop == nLength)
			bPossible = true;
	}
	return bPossible;
}
void test1()
{
	int pushOrder[5] = {1,2,3,4,5};
	int popOrder[5] = {4,3,5,2,1};
	if (IsPopOrder(pushOrder,popOrder,5))
	{
		printf("Yes!\n");
	}
	else
	{
		printf("No!\n");
	}
}
void test2()
{
	int pushOrder[5] = {1,2,3,4,5};
	int popOrder[5] = {4,3,5,1,2};
	if (IsPopOrder(pushOrder,popOrder,5))
	{
		printf("Yes!\n");
	}
	else
	{
		printf("No!\n");
	}
}
int main()
{
	test1();
	test2();
	return 0;
}
总结:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的
数字不在栈顶,我们把压栈序列中还没有入栈的数字压入辅助栈,知道把下一个需
要弹出的数字压入栈为止。如果所有的数字都压入了栈仍没有找到下一个弹出的数

字,那么该序列不可能是一个弹出的序列。


新的方法:

bool IsPopOrder(const int* arr1, const int* arr2, int length)
{
	if(arr1 == NULL || arr2 == NULL || length <= 0)
		return false;

	stack<int> arr1Stack;
	
	int i=0,j=0;
	while(i<=length && j<=length)	//防止第一个数组遍历到末尾就退出循环
	{
		if(arr1[i] == arr2[j])
		{
			++i;
			++j;
		}
		else if(arr1Stack.empty() || arr1Stack.top() != arr2[j])
		{
			arr1Stack.push(arr1[i]);
			++i;
		}
		else
		{
			arr1Stack.pop();
			++j;
		}
	}

	if(i>length && j>length)
		return true;
	else
	{
		return false;
	}
}


==参考剑指OFFER

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值