栈的压入和弹出序列

/*
 * 栈的压入和弹出序列.cpp
 *
 *  Created on: 2018年4月17日
 *      Author: soyo
 */
#include<iostream>
#include<stack>
using namespace std;
int judgeStack(int a[],int b[])
{
    stack<int> s;
    int i=0;
    int k=0;  //用来计数
    for(int j=0;j<5;j++)
    {
        if(s.empty()||s.top()!=b[i])
        {
            s.push(a[j]);
            k++;
        }
        while(s.top()==b[i])
        {
            s.pop();
            i++;
            k--;
            if(k==0)
                return 1;
        }
    }
    if(k!=0)
      return 0;


}
int main()
{
    int InStack[5]={1,2,3,4,5};
    int outStack[5]={4,5,3,2,1};
    //int outStack[5]={4,3,5,1,2};
   int find=judgeStack(InStack,outStack);
   cout<<find<<endl;
   if(find==1)
   {
        cout<<"第二个序列是第一个序列的弹出顺序"<<endl;
   }
   else{
       cout<<"不是弹出顺序"<<endl;
   }
}

结果:

1
第二个序列是第一个序列的弹出顺序

posted @ 2018-04-17 20:45  soyosuyang  阅读(198)  评论(0编辑  收藏  举报