您的位置:首页 > 运维架构

谈谈如何判断一个Pop序列是否是一个Push序列的Pop顺序

2011-07-29 14:57 591 查看
有这样一道题目:
输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。

我们来模拟入栈和出栈的过程:
这里有三个角色:
Push序列:它的动作只有一个那就是不断地将自己的元素一个个Push到栈Stack中,直到结束;
Stack栈:它的动作则有两个,一个是将传入的元素Push进来,一个是将已有的元素Pop出去,Push的元素来自Push序列,Pop的元素则从Pop序列中输出;
Pop序列:它的动作也只有一个,那就是不断的接收来自Stack栈Pop出来的元素并打印出来;


假定在某个时刻,Push序列刚好把元素A压入栈Stack中,Pop序列刚好将Stack栈Pop的元素B输出,B的输出有三种情况:
1. Stack弹出一个元素;
2. A压入并立即弹出;
3. A压入,再压入S2中的若干元素,然后弹出一个元素;
不满足上述条件,说明这个Pop序列不是Push序列对应的Pop顺序;

此时B的可能情况有:
1. B是Stack栈顶的元素C,这种情况是Stack把栈顶元素弹出;
2. B就是元素A,这种情况是A刚被Push进去,就被Pop出来了,因此B等于A;
3. 如果不是1和2,说明B只能是S2中的元素,因此,此时应该把A压入栈中,然后继续下一部,依次取出S2中的元素再次做上述比较;
4. 步骤2、3需要满足Push序列尚未结束,如果1、2、3都不满足,说明这个Pop序列不是Push序列的对应Pop顺序。

因此,我们得到这样一段代码:

#include <iostream>
#include <stack>

using namespace std;

bool isPopSequence(const int pushArray[], const int popArray[], int _size){
const int *pPush=pushArray;
const int *pPop=popArray;
stack<int> stData;
int cnt=0;
while(pPop - popArray < _size){
if((pPush - pushArray) >= _size && stData.empty())
break;
//if the push queue is still not empty, then push the element into the queue, and continue
if(!stData.empty() && stData.top() == *pPop){
stData.pop();
pPop++;
}
//if current element is equal to the element in pop queue, both move forward
else if((pPush - pushArray) < _size && *pPush == *pPop){
pPush++;
pPop++;
}
//if the top element of the stack is equal to current element, the pop it, pop queue move forward
else if((pPush - pushArray) < _size){
stData.push(*pPush);
pPush++;
}
//else the sequence is not matched
else
return false;
}
return true;
}

int main(){
int a[5]={1,2,3,4,5};
int b[5]={2,5,4,3,1};
if(isPopSequence(a,b,5))
cout<<"True"<<endl;
else
cout<<"False"<<endl;

return 0;
}


测试结果为:
True
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐