每日一算法(已知进栈序列 判断出栈序列是否合法)

#include<iostream>
using namespace std;

bool ifpossible(int*,int*,int);

void main()
{
 int lhs[]={1,2,3,4,5};
 int rhs[]={4,3,2,1,5};

 cout<<ifpossible(lhs,rhs,5)<<endl;
}

bool ifpossible(int *in,int *out,int len)
{
 int num=0;
 int *stack=new int[len];
 int *end=in+len;
 for(int i=0;i<len;i++)
 {
  if(num!=0&&*(stack+num-1)==*out)
  {
   --num;                 
   cout<<"no top"<<endl;
  }
  else
  {
   if(in==end)
    return false;
   while(in!=end&&*in!=*out)
   {
    if(in==end)
     return false;
    else
    {
     *(stack+num)=*in;
        in++;
        num++;
    }
   }
   if(in!=end)
   {
    in++;
   }
  }
  out++;
 }
 return true;
}

 

 

写完  没怎么全面测试,各位网友可以试试看看那里可以改进?或者有bug?不断学习中

posted on 2012-05-29 00:44  cs_jin_scor  阅读(648)  评论(0编辑  收藏  举报