判断元素出栈、入栈顺序的合法性

        输入两个整数序列,第一个整数序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出序列???   

       解决该问题很直观的想法就是建立一个辅助栈,根据弹出序列知第一个希望被弹出的数字为X,由于压入栈的顺序由压栈序列确定,所以此时应该把压入序列中X之前的 数字都依次压人到辅助栈里面去。如果下一个被弹出的数字刚好是栈顶数字,那么直接将其弹出,如果下一个弹出的数字不在栈顶,我们则把压栈序列中还没有入栈的数字(并且在该弹出数字之前的数字)压入辅助栈,如果所有的压栈序列中数字都遍历了仍然没有找到下一个弹出的数字,那么该序列就不可能是一个弹出序列。

 1 #include<iostream>  
 2 #include<stack>  
 3 using namespace std;
 4 bool Is_Legle( const char *pPush, const char *pPop)
 5 {
 6     stack<int>  s;
 7     if (strlen(pPush) != strlen(pPop))
 8     {
 9         return false;
10     }
11     while (*pPush != '\0')
12     {
13         if (*pPush != *pPop)
14         {
15             s.push(*pPush);
16         }
17         else
18         {
19             pPop++;
20             while (!s.empty() &&s.top() == *pPop)
21             {
22                 s.pop();
23                 pPop++;
24             }
25         }
26         pPush++;
27     }
28     if (s.empty() && *pPop == '\0')
29     {
30         return true;
31     }
32     else
33     {
34         return false;
35     }
36 }
37 void main()
38 {
39     char *dest = "12345";
40     char *src = "32415";
41     cout << Is_Legle(dest,src);
42     system("pause");
43 }

 

       

posted @ 2016-05-15 11:40  A_carat_tear  阅读(690)  评论(0编辑  收藏  举报