栈的push、pop序列(29)

来源:互联网 发布:php setcookie 作用域 编辑:程序博客网 时间:2024/06/05 10:32

29.栈的push、pop序列
题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。 

比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
因为可以有如下的push和pop序列:
push 1,push 2,push 3,push 4,pop,push 5,pop,pop,pop,pop,
这样得到的pop序列就是4、5、3、2、1。
但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

 

#include<iostream>#include<iomanip>using namespace std;/*下面的代码演示了如何写一个堆栈类,数组的个数传进来,类型用模板 */template<typename T>class stack{      public:             stack(int len):m_top(-1),m_len(len)             {                this->m_stack=new T[len];             }             ~stack()             {                delete []m_stack;                // 错误的写法 delete m_stack;              }             bool empty()              {                if(-1==m_top)                   return true;                else                   return false;             }             T top()             {                 return m_stack[m_top];             }             const T pop()             {                  return m_stack[m_top--];             }             void push(T v)             {                  if(m_top>=m_len-1)                     return ;                  else                     m_stack[++m_top]=v;             }      private:              int m_top;              T *m_stack;              const int m_len;              //大小,定义成 const类型 };bool cfun(int *a,int *b,const int len)//len 代表序列长度 {     int i,j;     bool bl;     stack<int> mystack(len);     for(i=0,j=0,bl=false;i<len&&j<len;)     //错误的写法:for(i=0,j=0,bl=false;i<len,j<=len;)      {        if(!bl)        // 为空或者不等于b[j]就压入新元素         {           mystack.push(a[i]);        }        if(!mystack.empty()&&mystack.top()==b[j])        {           mystack.pop();           j++;           bl=true;        }        else        {            bl=false;            i++;        }     }     if(mystack.empty())        return true;     else        return false;}int main(){    int a[]={1,2,3,4,5};    int b[]={4,3,5,1,2};    bool bl=cfun(a,b,5);    if(bl)      cout<<"yes";    else      cout<<"no";    cout<<endl;    system("pause");    return 0;}


函数cfun中的bool变量bl代表要不要将数据压入栈中,最开始需要压入数据,以后则是为空或者栈顶元素不等于b[j]压入元素。最后如果栈为空,那么说明是一个pop序列