zoukankan      html  css  js  c++  java
  • 面试题20:栈的压入、弹出序列


    思路:如果下一个弹出的数字刚好是栈顶数字,则直接弹出。若下一个弹出的数字不在栈顶,则把压栈序列中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。若所有的数字都压入栈了仍没有找到下一个弹出的数字,则表明该序列不可能滴一个弹出序列。

    代码:

    #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;
    }
    


  • 相关阅读:
    oracle连接本地数据库
    ERWin 7.2下载安装及注册机
    关于oracle中to_char和to_date的用法
    2016年11月26号随笔(关于oracle数据库)
    SQL Server Browser服务的作用
    正则表达式
    server重启导致执行包的job运行失败
    Windows Log和SQL SERVER errorlog
    windows services创建和部署
    c# 读取App.config
  • 原文地址:https://www.cnblogs.com/dyllove98/p/3206463.html
Copyright © 2011-2022 走看看