首页 > 其他 > 详细

栈的压入、弹出序列

时间:2014-03-12 21:14:41      阅读:442      评论:0      收藏:0      [点我收藏+]
/************************************************************
题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二
个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如
序列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;
}
总结:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的
数字不在栈顶,我们把压栈序列中还没有入栈的数字压入辅助栈,知道把下一个需
要弹出的数字压入栈为止。如果所有的数字都压入了栈仍没有找到下一个弹出的数

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

==参考剑指OFFER

栈的压入、弹出序列,布布扣,bubuko.com

栈的压入、弹出序列

原文:http://blog.csdn.net/walkerkalr/article/details/21107755

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!