您的位置:首页 > 职场人生

【剑指offer 面试题22】栈的压入、弹出序列

2015-07-06 22:17 567 查看
思路:

  不停地压栈,直到栈头元素与弹出序列的首元素相等则出栈,同时弹出序列后移;若不相等则一直保持压栈,直到压入所有元素后弹出序列仍不为空,则说明无法匹配。

C++:

#include<iostream>
#include<vector>
#include<stack>
usingnamespacestd;

boolIsPreOrder(vector<int>&pushVec,vector<int>&popVec)
{
if(pushVec.size()!=0&&popVec.size()!=0)
{
vector<int>::iteratoritPush=pushVec.begin();
vector<int>::iteratoritPop=popVec.begin();

stack<int>_stack;

while(itPop!=popVec.end())
{
while(_stack.empty()||_stack.top()!=*itPop)
{
if(itPush==pushVec.end())
break;

cout<<"push:"<<*itPush<<endl;
_stack.push(*itPush);
itPush++;
}

if(_stack.top()!=*itPop)
break;

cout<<"pop:"<<_stack.top()<<endl;
_stack.pop();
itPop++;
}

if(_stack.empty()&&itPop==popVec.end())
returntrue;
}
returnfalse;
}

intmain()
{
intapush[]={1,2,3,4,5};
intapop1[]={4,5,3,2,1};
intapop2[]={4,3,5,1,2};

vector<int>vpush(apush,apush+5);
vector<int>vpop1(apop1,apop1+5);
vector<int>vpop2(apop2,apop2+5);
cout<<"push:12345pop:45321"<<endl;
cout<<"res="<<IsPreOrder(vpush,vpop1)<<endl<<endl;
cout<<"push:12345pop:43512"<<endl;
cout<<"res="<<IsPreOrder(vpush,vpop2)<<endl;
}


测试结果:


push:12345pop:45321
push:1
push:2
push:3
push:4
pop:4
push:5
pop:5
pop:3
pop:2
pop:1
res=1


push:12345pop:43512
push:1
push:2
push:3
push:4
pop:4
pop:3
push:5
pop:5
res=0


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