#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;
}
【100题】给定入栈序列,判断一个序列是否可能为输出序列
最新推荐文章于 2022-01-15 09:29:15 发布