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

【算法】输入两个整数序列。其中一个序列表示栈的push顺序,判断另一个序列有没有可能是对应的pop顺序。

2012-10-02 17:05 645 查看
输入两个整数序列。其中一个序列表示栈的push 顺序,判断另一个序列有没有可能是对应的pop 顺序。

为了简单起见,我们假设push 序列的任意两个整数都是不相等的。

比如输入的push 序列是1、2、3、4、5,那么4、5、3、2、1 就有可能是一个pop 系列,但序列4、3、5、1、2 就不可能是push 序列1、2、3、4、5 的pop 序列。

思路:

1.首先新建一个栈模拟入栈入栈,都是在push序列中进行。

2.将push序列依次开始入栈,直到栈顶元素等于pop序列的第一个元素。

3.push的栈顶元素出栈,pop序列移到第二元素。

4.如果push栈顶继续等于pop序列现在的元素,则继续出栈并pop后移。

5.如果push已经全部入栈但是pop序列未遍历结束,且栈顶元素不等于现在所指元素则返回false。

6.如果栈为空,且pop也已经遍历结束,则返回true

按照上述思路,给出了源代码:代码中有两个实现,其中第一个是按照我的思路实现的,另外一个是网上的答案。
#include <iostream>
#include <stack>
using namespace std;

bool isPopSerial(int push[], int pop[], int n)//我自己写的一种方法,注意函数名
{
int i=0,j=0;
stack<int> mystack;
while(i < n)//只要没有全部将push数组push到栈中
{
mystack.push(push[i]);
i++;
while(!mystack.empty() && mystack.top() == pop[j])
{
mystack.pop();
j++;
}

}
if( mystack.empty() && j==n)//最后是pop序列的唯一条件:栈变空了,且pop序列游标到了最后
return true;
return false;//除此之外都不是pop序列

}

bool isPopSeries(int push[],int pop[],int length)//网上流传的经典答案
{
if(!push||!pop||length<=0)
return false;
stack<int> temp;
int pushNum=0;
int i = 0;
while(i < length)
{
while(temp.empty()||temp.top()!=pop[i])
{
if(pushNum < length)
temp.push(push[pushNum++]);
else
return false;
}
if(!temp.empty()&&temp.top()==pop[i])
{
temp.pop();
i++;
}
}
return true;
}

int main()
{
int pushArray[5] = {1,2,3,4,5};
int popArray[5] = {4,5,3,2,1};
if(isPopSerial(pushArray,popArray,5))
cout<<"yes"<<endl;
else
cout<<"no"<<endl;

return 0;
}


 

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