首页 > 代码库 > 栈的压入弹出序列

栈的压入弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。

代码:

#include <iostream>
#include <stack>
#include <assert.h>


using namespace std;

bool isStackSeq(int *pPush,int *pPop,int length){
	bool isstack = false;
	if(pPush != NULL && pPop != NULL && length > 0){

		const	int *pPushNext = pPush;
		const   int *pPopNext = pPop;

		stack<int> stackData;

		while(pPopNext - pPop < length){
			//将元素入栈
			while(stackData.empty() ||  stackData.top()  !=  *pPopNext){

				if(pPushNext - pPush == length)
						break;
				
				stackData.push(*pPushNext);
				
				pPushNext ++;
			}
			if(stackData.top() != *pPopNext)
			break;
			
			stackData.pop();
			pPopNext ++;
		}
		if(stackData.empty() && pPushNext - pPush == length)
			isstack = true;

	}

	return isstack;
}



int main()
{	
	int data1[] = {1,2,3,4,5};
	int data2[] = {4,5,3,2,1};
	cout<< isStackSeq(data1,data2,sizeof(data1)/sizeof(int));

    return 0;
}

运行结果: