输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。
程序一:
参考file:///F:/专业资料/微软面试题/题目:输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。%20-%20Mr_Willy的专栏%20-%20博客频道%20-%20youkuaiyun.com.mht
bool isPopSerial(int input[], int output[], int length)
{
stack<int> s;
int pushnum=0;
int i=0;
while(i<length)
{
while(s.empty() || s.top()!=output[i])
{
if(pushnum < length)
s.push(input[pushnum++]);
else
return false;
}
while(!s.empty() && s.top()==output[i])
{
s.pop();
i++;
}
}
return true;
}
程序二:参见http://www.189works.com/article-14048-1.html
bool isStackPushPop(int a[], int b[], int n)
{
stack<int> s;
int i=-1, j=0;//i=-1,以及后面的a[++i]是正确的关键;改成i=0, a[i++]就不对了
while(i<n && j<n)
{
if(s.empty() || s.top() != b[j])
s.push(a[++i]);
else
{
s.pop();
j++;
}
}
return s.empty();
}
程序三:参见http://zhedahht.blog.163.com/blog/static/25411174200732102055385/
bool IsPossiblePopOrder(const int* pPush, const int* pPop, int nLength)
{
bool bPossible=false;
if(pPush && pPop && nLength>0)
{
const int *pNextPush=pPush;
const int *pNextPop=pPop;
stack<int> s;
while(pNextPop - pPop < nLength)
{
while(s.empty() || s.top()!=*pNextPop)
{
if(!pNextPush)
break;
s.push(*pNextPush);
if(pNextPush-pPush <nLength-1)
pNextPush++;
else
pNextPush=NULL;
}
if(s.top() != *pNextPop)
break;
s.pop();
pNextPop++;
}
if(s.empty() && pNextPop-pPop==nLength)
bPossible=true;
}
return bPossible;
}