【问题描述】给出一个堆栈的输入序列,试判断一个序列是否能够由这个堆栈输出。如果能,返回总的出栈次数,如果不能,返回0。序列的输入及输出都是从左往右。(输入输出序列皆为整数且没有重复的数字,如果一个数字在输入序列中没有出现,那么其在输出序列中也不会出现)
【输入形式】第一行为输入序列的长度(长度不超过100),然后为输入序列的数字;第二行为输出序列的数字。输入数据以空格隔开。
【输出形式】如果是一个出栈序列,则返回总的出栈次数, 否则返回0
【样例输入】
5 1 2 3 4 5
1 2 3 4 5
【样例输出】5
【样例说明】第一行输入的第一个数字是序列的长度,1 2 3 4 5 输入序列,以空格隔开,输出的总的出栈次数。
【实现要求】
用栈操作实现。
#include <iostream>
#include <stdlib.h>
using namespace std;
#define MaxSize 100
int n,pop=0;
int arr1[110],arr2[110];
typedef struct
{
int data[MaxSize];
int top;
}SqStack;
void InitStack(SqStack *&s)
{
s=(SqStack *)malloc(sizeof(SqStack));
s->top=-1;
}
bool StackEmpty(SqStack *s)
{
return (s->top==-1);
}
bool Push(SqStack *&s,int e)
{
if(s->top==MaxSize-1) return false;
s->top++;
s->data[s->top]=e;
return true;
}
void Pop(SqStack *&s)
{
s->top--;
}
int GetTop(SqStack *s)
{
return s->data[s->top];
}
int main()
{
SqStack *s;
int i,m=0,flag;
InitStack(s);
cin>>n;
for(i=0;i<n;i++)
cin>>arr1[i];
for(i=0;i<n;i++)
cin>>arr2[i];
for(i=0;i<n;i++)//在输入数组中寻找输出数组中的以第1个元素
{
if(arr1[i]==arr2[0])
{
m=i;
break;//找到了第一个元素,用m记下来
}
}
if(i==n) //没找到,则不用在做其他操作,直接输出0结束
{
cout<<"0";
return 0;
}
for(i=0;i<=m;i++)//将输入数组中前m个元素进栈
{
Push(s,arr1[i]);
}
for(i=0;i<n;i++)
{
if(!StackEmpty(s)&&GetTop(s)==arr2[i])//输入序列之前的元素不为输出
{
Pop(s);
pop++;
}
else
{
flag=0;
m++;
while(flag!=1)
{
if(m==n-1)
{
if(arr1[m]==arr2[i])//m之后的元素为输出元素
{
flag=1;
pop++;
}
else
{
cout<<"0";
return 0;
}
}
else if(m==n)
{
cout<<"0";
return 0;
}
else
{
if(arr1[m]==arr2[i])
{
flag=1;
pop++;
}
else
{
Push(s,arr1[m]);
m++;
}
}
}
}
}
cout<<pop;
return 0;
}