【问题描述】
给出一个堆栈的输入序列,试判断一个输出序列是否能够由这个堆栈输出。如果能,返回总的出栈次数,如果不能,输出0。
序列的输入及输出都是从左往右。(输入输出序列皆为整数且没有重复的数字,如果一个数字在输入序列中没有出现,那么其在输出序列中也不会出现)
【输入形式】
第一行为输入序列的长度,其后依次为输入序列的数字;
第二行为输出序列的数字。
输入数据以空格隔开。
【输出形式】
如果是一个正确的出栈序列,则输出总的出栈次数, 否则返回0
【样例输入1】
5 1 2 3 4 5
4 5 3 2 1
【样例输出1】
5
【样例说明1】可以按以下顺序执行:
push(1), push(2), push(3), push(4), pop() -> 4, push(5), pop() -> 5, pop() -> 3, pop() -> 2, pop() -> 1
通过5次pop操作可以得到输出序列,因此返回5
【样例输入2】
5 1 2 3 4 5
4 3 5 1 2
【样例输出2】0
【样例说明2】1不能在2之前输出,因此返回0
【评分标准】
填充主函数代码,调用堆栈基本操作完成输出序列判断。
#include
#include
#include
#define ERROR 0
#define OK 1
#define INIT_SIZE 100
#define INCREMENT 20typedef int ElemType;
typedef struct SqStack{
ElemType *base,*top;
int stacksize;
}SqStack;
int InitStack(SqStack *S)
{
S->base=(ElemType *)malloc(INIT_SIZE*sizeof(ElemType));
if(!S->base) return ERROR;
S->top=S->base;
S->stacksize=INIT_SIZE;
return OK;
}
int Empty(SqStack *S)
{
if(S->top==S->base){
return OK;
}else{
return ERROR;
}
}
int Push(SqStack *S,ElemType e)
{
if(S->top-S->base>=S->stacksize){
S->base=(ElemType*)realloc(S->base,(S->stacksize+INCREMENT)*sizeof(ElemType));
if(!S->base) return ERROR;
S->top=S->base+S->stacksize;
S->stacksize+=INCREMENT;
}
*S->top++=e;//*s->top=e;s->top++;
return OK;
}
int Pop(SqStack *S,ElemType *e)
{
if(S->top==S->base) return ERROR;
*e=*--S->top;//s->top--;*e=*s->top;
return OK;
}
int GetTop(SqStack *S,ElemType *e)
{
S->top--;
*e=*S->top;
S->top++;
return OK;
}
int main()
{
SqStack s;
ElemType e;
InitStack(&s);
int in[100];
int out[100];
int n=0,m=0;
int rec = 0;
scanf("%d", &n);
for(int i=0;i
scanf("%d", &in[i]);
}
for(;scanf("%d", &out[m])==1;m++);
int aa=0,bb=0;
while(bb
if(Empty(&s)){
Push(&s, in[aa++]);
continue;
}
GetTop(&s, &e);
if(e!=out[bb]){
Push(&s, in[aa++]);
}else{
Pop(&s,&e);
bb++;
rec++;
}
}
if(bb==m){
printf("%d",rec);
}else{
printf("0");
}
return 0;
}