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 }
  • 相关阅读:
    SVN服务器搭建(一)
    排序算法二:冒泡排序
    【LeetCode】136. Single Number
    【LeetCode】217. Contains Duplicate
    【LeetCode】189. Rotate Array
    【LeetCode】122. Best Time to Buy and Sell Stock II
    【LeetCode】26. Remove Duplicates from Sorted Array
    【LeetCode】20. Valid Parentheses
    【LeetCode】680. Valid Palindrome II
    【LeetCode】345. Reverse Vowels of a String
  • 原文地址:https://www.cnblogs.com/raichen/p/5648789.html
Copyright © 2011-2022 走看看