设一个栈的输入序列为1,2,3,...,n-1,n。请编写一个算法,判断一个序列p1,p2,p3,...,pn

是否是一个有效的栈输出序列。若有效输出1,无效输出0。
这要怎么做啊,求大家帮帮忙啊,我不懂的分析啊

第1个回答  2014-10-23
#include<stdio.h>

#define StackLen 50
#define DLen 10

int Pop[DLen]={7,10,9,8,6,5,4,3,2,1},pPop=0;

int DS[StackLen],pDS=-1;
int pPush=0,iStep=0;

int fPush(int d);
int fPop();

void main()
{
int i;
for(;pPop<DLen;pPop++)
{
for(i=pPush;i<Pop[pPop];i++)
{
fPush(pPush+++1);
//pPush++;
}
if(fPop()!=Pop[pPop])
{
printf("ERROR! I Can not find a way to pop the data!\n");
return;
}
}
printf("Mission is well done!\n");
}

int fPush(int d)
{
if(pDS>=StackLen){printf("Stack Overflow!\n");return -1;}
DS[pDS++]=d;
printf("%d:Push %d in Stack[%d]\n",iStep++,d,pDS);
return d;
}

int fPop()
{
int d;
if(pDS<0){printf("Stack empty!\n");return -1;}
d=DS[--pDS];
printf("%d:Pop %d from Stack[%d]\n",iStep++,d,pDS+1);
return d;
}
相似回答