【面试题22】栈的压入、弹出序列

【题目描述】

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列,假设压入栈的所有数字不相等。

例如序列1,2,3,4,5是某栈的压栈顺序,序列4,5,3,2,1是该栈对应的一个弹出序列,但是4,3,5,1,2就不可能是该压栈顺序的弹出序列。

【解决方案】

 1         public static bool IsPopOrder(int[] pushOrder, int[] popOrder)
 2         {
 3             if (pushOrder == null || popOrder == null || pushOrder.Length < 1 || popOrder.Length < 1)
 4             {
 5                 return false;
 6             }
 7 
 8             Stack<int> stack = new Stack<int>();
 9             int pushIndex = 0;
10 
11             foreach (int num in popOrder)
12             {
13                 if (stack.Count > 0 && stack.Peek() == num)
14                 {
15                     stack.Pop();
16                     continue;
17                 }
18 
19                 if (pushIndex == pushOrder.Length)
20                     return false;
21 
22                 while (pushIndex < pushOrder.Length)
23                 {
24 
25                     if (pushOrder[pushIndex] != num)
26                     {
27                         stack.Push(pushOrder[pushIndex]);
28                         pushIndex++;
29                     }
30                     else
31                     {
32                         pushIndex++;
33                         break;
34                     }
35                 }
36             }
37 
38             return true;
39         }
原文地址:https://www.cnblogs.com/HuoAA/p/4806453.html