海涛老师的面试题-作业22-栈的压入、弹出序列
2012-06-29 15:25
239 查看
题目:输入两个整数序列,第一个序列表示栈的压入顺序,判断第二个序列是否是该栈的弹出顺序,假设压入栈的所有数字均不相等,例如序列 1 2 3 4 5 是压栈顺序,而4 5 3 2 1是该压栈的序列对应的一个弹出序列,但是 4 3 5 1 2 不可能是该压栈序列的弹出序列
View Code
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; }
相关文章推荐
- 面试题22:栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 剑指offer之面试题22:栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22:栈:栈的压入和弹出序列
- 面试题22:栈的压入、弹出序列
- 剑指Offer——面试题22:栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22_栈的压入和弹出序列
- 面试题22 栈的压入、弹出序列
- P134、面试题22:栈的压入、弹出序列
- [剑指offer]面试题22:栈的压入、弹出序列
- 举例让抽象具体化-面试题22-栈的压入、弹出序列
- 【剑指offer】面试题22:栈的压入、弹出序列
- 剑指Offer之面试题22:栈的压入、弹出序列
- 面试题22 栈的压入、弹出序列
- 剑指Offer:面试题22 栈的压入、弹出序列
- 剑指Offer面试题22(Java版):栈的压入、弹出序列
- 剑指offer_面试题22_栈的压入、弹出序列(总结规律)