面试题20:栈的压入、弹出序列
来源:互联网 发布:淘宝前十女装店 编辑:程序博客网 时间:2024/05/21 08:42
思路:如果下一个弹出的数字刚好是栈顶数字,则直接弹出。若下一个弹出的数字不在栈顶,则把压栈序列中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。若所有的数字都压入栈了仍没有找到下一个弹出的数字,则表明该序列不可能滴一个弹出序列。
代码:
#include "stdafx.h"#include <iostream>#include <stack>using namespace std;bool IsPopOrder(int *pPush, int *pPop, int nLength){ if (pPush == NULL || pPop == NULL || nLength <= 0) { return false; } stack<int> s; s.push(pPush[0]); int nPop_index = 0; int nPush_index = 1; while (nPop_index < nLength) { while (s.top() != pPop[nPop_index] && nPush_index < nLength) { s.push(pPush[nPush_index]); nPush_index++; } if (s.top() == pPop[nPop_index]) { s.pop(); nPop_index++; } else { return false; } } return true;}int _tmain(int argc, _TCHAR* argv[]){int nPush[5] = {1,2,3,4,5};int nPop1[5] = {4,5,3,2,1};int nPop2[5] = {4,3,5,1,2}; int nPop3[5] = {5,4,3,2,1};int nPop4[5] = {4,5,2,3,1};cout << IsPopOrder(nPush, nPop1, 5) << endl;cout << IsPopOrder(nPush, nPop2, 5) << endl;cout << IsPopOrder(nPush, nPop3, 5) << endl;cout << IsPopOrder(nPush, nPop4, 5) << endl; system("pause");return 0;}
- 面试题20:栈的压入、弹出序列
- 【面试题二十二】栈的压入、弹出序列
- 面试题整理6 栈的压入、弹出序列
- 栈的压入、弹出序列(面试题 22)
- 面试题22:栈的压入弹出序列
- 面试题22栈的压入、弹出序列
- 面试题22 栈的压入弹出序列
- 面试题22:栈的压入弹出序列
- 面试题22:栈的压入、弹出序列
- 【经典面试题】栈的压入弹出序列
- 面试题26:栈的压入、弹出序列
- 栈的压入、弹出序列(剑指offer面试题)
- 剑指offer面试题 栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22 栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22:栈的压入、弹出序列
- 面试题22栈的压入弹出序列
- 这11道题据说要智商200的人才能全解出来
- Expdp For Metadata Is Slow In 11.2.0.3 With Partitioned Objects [ID 1466040.1]
- 在.NET使用JSON作为数据交换格式(转http://blog.csdn.net/zhoufoxcn/article/details/6254657)
- YUV数据占用内存大小
- 程序员的八个级别
- 面试题20:栈的压入、弹出序列
- 黑马程序员--Java基础--异常
- 编程调试和诊断的五大规则
- [转自博客园]Android网络连接判断与处理
- 自己动手设计代码编辑器——(六)自己写XML管理类
- ADO的数据泵
- EMV技术学习和研究(五)脱机数据认证之DDA
- 解决eclipse ADT编译NDK报NDK和minSdkVersion不匹配的问题
- windows KdPrint打印中文文件夹的问题,应该是DbgPrint的BUG