zoukankan      html  css  js  c++  java
  • 判断元素出栈、入栈顺序的合法性

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

           解决该问题很直观的想法就是建立一个辅助栈,根据弹出序列知第一个希望被弹出的数字为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 != '')
    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 == '')
    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 }

           

  • 相关阅读:
    HDU 4861 Couple doubi(数论)
    POJ 3233 Matrix Power Series 二分+矩阵乘法
    js原生offsetParent解析
    ADS-B显示终端6.8
    模板
    习题四——数字智力题
    Android ORMLite ForeignCollection关联外部集合
    Android应用程序无法读写USB设备的解决方法
    [学习笔记]批次需求计划-十一大量
    jqury+css实现可弹出伸缩层
  • 原文地址:https://www.cnblogs.com/-zyj/p/5494926.html
Copyright © 2011-2022 走看看