oral_quiz->#IsPopOrder#

[亡魂溺海] 提交于 2020-12-05 22:07:14
#include <stdio.h>
#include <stack>
#include <exception>

bool MyIsPopOrder(int* InSeq, int* OutSeq, int length) {
	if(InSeq == NULL || OutSeq == NULL || length <= 0)
		return false;

	std::stack<int> stackAid;

	int index = 0;
	for(int i=0; i<length; ++i) {
		if(!stackAid.empty() && OutSeq[i] == stackAid.top()) {
			stackAid.pop();
			continue;
		}
		while(index < length && InSeq[index] != OutSeq[i]) {
			stackAid.push(InSeq[index++]);
		}
		//push
		if(index < length && InSeq[index] == OutSeq[i])
			stackAid.push(InSeq[index]);
		if(!stackAid.empty() && OutSeq[i] != stackAid.top() && index >= length)
			return false;
		//pop
		if(index < length && InSeq[index] == OutSeq[i]) {
			stackAid.pop();
			++index;
		}
	}

	return true;
}

//============================hht's=========================
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;

		std::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 Test(const char* testName, int* InSeq, int* OutSeq, int length, bool expected) {
	if(testName != NULL)
		printf("%s begins: \n", testName);
//	if(expected == MyIsPopOrder(InSeq, OutSeq, length))
	if(expected == IsPopOrder(InSeq, OutSeq, length))
		printf("passed.\n");
	else
		printf("failed.\n");
}

//***********multi number***************
//1.yes
void Test1() {
	int InSeq[] = {1,2,3,4,5};
	int OutSeq[] = {3,5,4,2,1};
	Test("Test1", InSeq, OutSeq, 5, true);
}
//2.no
void Test2() {
	int InSeq[] = {1,2,3,4,5};
	int OutSeq[] = {4,3,5,1,2};
	Test("Test2", InSeq, OutSeq, 5, false);
}

//***********single number***************
//1.yes
void Test3() {
	int InSeq[] = {2};
	int OutSeq[] = {2};
	Test("Test3", InSeq, OutSeq, 1, true);
}
//2.no
void Test4() {
	int InSeq[] = {5};
	int OutSeq[] = {4};
	Test("Test4", InSeq, OutSeq, 1, false);
}

//NULL
void Test5() {
	Test("Test5", NULL, NULL, 0, false);
}

int main(int argc, char* argv[]) {
	Test1();
	Test2();
	Test3();
	Test4();
	Test5();

	return 0;
}



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!