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

海涛老师的面试题-作业22-栈的压入、弹出序列

2012-06-29 15:25 239 查看
题目:输入两个整数序列,第一个序列表示栈的压入顺序,判断第二个序列是否是该栈的弹出顺序,假设压入栈的所有数字均不相等,例如序列 1 2 3 4 5 是压栈顺序,而4 5 3 2 1是该压栈的序列对应的一个弹出序列,但是 4 3 5 1 2 不可能是该压栈序列的弹出序列

View Code

// 栈的压入弹出顺序.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include <stack>
#include <iostream>
using namespace std;

bool IsPopOrder(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>  stack;
while(pNextPop-pPop<nLength)
{
while(stack.empty()||stack.top()!=*pNextPop)
{
if(pNextPush-pPush==nLength)
break;
stack.push(*pNextPush);
pNextPush++;
}
if(stack.top()!=*pNextPop)
break;
stack.pop();
pNextPop++;
}
if(stack.empty()&&pNextPop-pPop==nLength)
bPossible=true;
}
return bPossible;
}

void Test1()
{
int arr[]={1,2,3,4,5};
int brr[]={4,5,3,2,1};
int crr[]={4,3,5,1,2};
bool a_bOrder=IsPopOrder(arr,brr,5);
bool a_cOrder=IsPopOrder(arr,crr,5);
int temp=a_bOrder*2+a_cOrder;
switch(temp)
{
case 0:
cout<<"Both are Not sequence!"<<endl;
break;
case 1:
cout<<"crr  are  The sequence!"<<endl;
break;
case 2:
cout<<"brr  are  The sequence!"<<endl;
break;
case 3:
cout<<"Both are sequence !"<<endl;
break;
default:
break;
}
}

int _tmain(int argc, _TCHAR* argv[])
{
Test1();
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: