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

    注意判断条件:

     1 bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
     2 {
     3     bool bPossible = false;
     4 
     5     if(pPush != NULL && pPop != NULL && nLength > 0)
     6     {
     7         const int* pNextPush = pPush;
     8         const int* pNextPop = pPop;
     9 
    10         std::stack<int> stackData;
    11 
    12         while(pNextPop - pPop < nLength)
    13         {
    14             // 当辅助栈的栈顶元素不是要弹出的元素
    15             // 先压入一些数字入栈
    16             while(stackData.empty() || stackData.top() != *pNextPop)
    17             {
    18                 // 如果所有数字都压入辅助栈了,退出循环
    19                 if(pNextPush - pPush == nLength)
    20                     break;
    21 
    22                 stackData.push(*pNextPush);
    23 
    24                 pNextPush ++;
    25             }
    26 
    27             if(stackData.top() != *pNextPop)
    28                 break;
    29 
    30             stackData.pop();
    31             pNextPop ++;
    32         }
    33 
    34         if(stackData.empty() && pNextPop - pPop == nLength)
    35             bPossible = true;
    36     }
    37 
    38     return bPossible;
    39 }

     我的代码:

     1 bool IsPopOrder(const int* pPush, const int* pPop, int nLength)
     2 {
     3     if (pPush == NULL || pPop == NULL || nLength == 0)
     4         return false;
     5 
     6     const int *pNextPush = pPush;
     7     const int *pNextPop = pPop;
     8 
     9     std::stack<int> stackData;
    10     while (nLength != 0)
    11     {
    12         while (nLength != 0 && *pNextPush != *pNextPop)
    13         {
    14             stackData.push(*pNextPush);
    15             pNextPush++;
    16             nLength--;
    17         }
    18         if(nLength != 0)
    19         {
    20             stackData.push(*pNextPush);
    21             pNextPush++;
    22             nLength--;
    23         }
    24         while (stackData.size() > 0 && stackData.top() == *pNextPop)
    25         {
    26             stackData.pop();
    27             pNextPop++;
    28         }
    29     }
    30     if (stackData.empty())
    31         return true;
    32     else
    33         return false;
    34 
    35 }
  • 相关阅读:
    浅谈Huffman树
    CF884D:Boxes And Balls
    MySQL单表查询(重要)
    MySQL字段完整性约束(重要)
    MySQL数据类型(重要)
    数据库基本操作
    MySQL权限管理
    MySQL存储引擎概述
    数据库基础
    并发编程小结
  • 原文地址:https://www.cnblogs.com/raichen/p/5648789.html
Copyright © 2011-2022 走看看