100题-29- push match pop?

题目:输入两个整数序列。其中一个序列表示栈的push顺序,
判断另一个序列有没有可能是对应的pop顺序。
为了简单起见,我们假设push序列的任意两个整数都是不相等的。
比如输入的push序列是1、2、3、4、5,那么4、5、3、2、1就有可能是一个pop系列。
因为可以有如下的push和pop序列:
push1,push2,push3,push4,pop,push5,pop,pop,pop,pop,
这样得到的pop序列就是4、5、3、2、1。

但序列4、3、5、1、2就不可能是push序列1、2、3、4、5的pop序列。

不使用堆栈的方法:

int push_pop(int *push,int *pop, int n)
{
    int step=1;
    int flag=1;
    int i,j;
    int locate;
    for(j=0;j<n;j++)
    {
        if(pop[0]==push[j])
        {
            locate = j;
            break;
        }
    }
    for(i=1;i<n;i++)
    {
             if((locate+flag)<n &&(locate+flag)>=0&& pop[i]==push[locate+flag])
            {
                locate=locate+flag;
                step++;
                continue;
            }
            else if((locate-flag*step)<n &&(locate-flag*step)>=0 && pop[i]==push[locate-flag*step])
            {
                locate = locate-flag*step;
                step++;
                flag=-flag;
                continue;
            }
            else
            {
                printf("not match!");
                return 0;
            }
    }
    printf("match!");
    return 0;
}

模拟堆栈的过程:(看上去这个方法简单一些,但是如果要自己写堆栈的函数的话,这个也不一定比上面的简单了)

int ispopseries(int push[],int pop[],int n)
{
    Stack s;
    InitStack(&s);
    int i=0,j=0;
    while(j<n)
    {
        while(IsEmpty(&s)||getTopElem(&s)!=pop[j])
            if(i<n)
                Push(&s,push[i++]);
             else
             {
                 printf("match pop and push!");
                 return 0;
             }
         while(!IsEmpty(&s)&&getTopElem(&s)==pop[j])
         {
             Pop(&s);
             j++;
         }
    }
    printf("match pop and push!");
    return 1;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值