1. 程式人生 > >【100題】給定入棧序列,判斷一個序列是否可能為輸出序列

【100題】給定入棧序列,判斷一個序列是否可能為輸出序列

#include <stack>
#include <iostream>
using namespace std;

/*
假設序列中無重複數字
輸入序列為: 1,2,3,4,5
測試序列:4,5,3,2,1
測試序列:4,3,5,1,2

題目拓展:
1,如果序列中有重複的元素,怎麼辦?
2,找出一個入棧序列中所有可能的出棧序列?
*/

bool bxy
(
	const int *pPush,
	const int *pPop,
	int nLength
)

{
	bool flag = false;
	if(pPush && pPop && nLength>0)
	{
		const int *pNextPush = pPush;
		const int *pNextPop = pPop;

		stack<int> data;

		while(pNextPop-pPop < nLength)
		{
			//當data為空,而且棧頂元素不是pop序列當前的值
			//則向data中push

			while(data.empty() || data.top() != *pNextPop)
			{
				//如果push序列為空,則跳出!
				if(!pNextPush)
				{
					break;
				}
				//
				data.push(*pNextPush);
				if(pNextPush-pPush < nLength-1)
				{
					pNextPush++;
				}
				else
				{
					break;
					//pNextPush = NULL;
				}
			}
			//
			if(data.top() != *pNextPop)
			{
				break;
			}
			data.pop();
			pNextPop++;
		}
		if(data.empty() && pNextPop-pPop==nLength)
		{
			flag = true;
		}
	}
	return flag;
}

int main(int argc, char **argv)
{
	int push[] = {1,2,3,4,5};
	int Yespop[] = {4,5,3,2,1};
	int Nopop[] = {4,3,5,1,2};
	
	cout << bxy(push,Yespop,5) <<endl;
	cout << bxy(push,Nopop,5) <<endl;

	return 0;
}