29.栈的push、pop序列(栈)
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
因为可以有如下的push和pop序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的pop序列就是4、5、3、2、1。
但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。
//coder:Lee,20120318
#include<iostream>
#include<cassert>
#include<stack>
using namespace std;
///
//Give you a push order and whether an array is to be its corresponding pop order
//Input: PushList -an array of integers, the push order
// PopList -an array of integers, the pop order
// length -the length of PushList and PopList
//Output: If pPop is possible to be the pop order of pPush, return true.Otherwise return false
///
bool CompareTwoSequences(const int *PushList,const int *PopList,int length)
{
assert(PushList!=NULL&&PopList!=NULL&&length>0);
// ancillary stack
stack <int> s;
int index=0;
for (int i=0;i<length;i++)
{
//if the stack is empty ,push an integer into the stack
if(s.empty())
s.push(PushList[index++]);
//continue to push an integer into the stack until we get needed pop number
while(s.top()!=PopList[i])
{
if(index<length)
s.push(PushList[index++]);
//index==length means all integers have been pushed into the stack
else
return false;
}
//check next integer
s.pop();
}
return true;
}
int main()
{
int PushList[5]={1,2,3,4,5};
int PopList[5]={4,5,3,2,1};
cout<<CompareTwoSequences(PushList,PopList,5);
return 0;
}
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
因为可以有如下的push和pop序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的pop序列就是4、5、3、2、1。
但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。
//coder:Lee,20120318
#include<iostream>
#include<cassert>
#include<stack>
using namespace std;
///
//Give you a push order and whether an array is to be its corresponding pop order
//Input: PushList -an array of integers, the push order
// PopList -an array of integers, the pop order
// length -the length of PushList and PopList
//Output: If pPop is possible to be the pop order of pPush, return true.Otherwise return false
///
bool CompareTwoSequences(const int *PushList,const int *PopList,int length)
{
assert(PushList!=NULL&&PopList!=NULL&&length>0);
// ancillary stack
stack <int> s;
int index=0;
for (int i=0;i<length;i++)
{
//if the stack is empty ,push an integer into the stack
if(s.empty())
s.push(PushList[index++]);
//continue to push an integer into the stack until we get needed pop number
while(s.top()!=PopList[i])
{
if(index<length)
s.push(PushList[index++]);
//index==length means all integers have been pushed into the stack
else
return false;
}
//check next integer
s.pop();
}
return true;
}
int main()
{
int PushList[5]={1,2,3,4,5};
int PopList[5]={4,5,3,2,1};
cout<<CompareTwoSequences(PushList,PopList,5);
return 0;
}