面试题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 }
原文地址:https://www.cnblogs.com/raichen/p/5648789.html