剑指Offer系列---(24)栈的压入、弹出序列

1.题目描述:
输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假如压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压栈序列,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。
2.分析:
判断一个序列是不是栈的弹出序列的规律:如果下一个弹出的数字刚好是栈顶数字,那么直接弹出。如果下一个弹出的数字不在栈顶,我们把压栈序列中还没有入栈的数字压入辅助栈,直到把下一个需要弹出的数字压入栈顶为止。如果所有的数字都压入栈了仍然没有找到下一个弹出的数字,那么该序列不可能是一个弹出序列。
3.源代码:

#include <iostream>
#include <stack>
using namespace std;

bool IsPopOrder(int *pPush,int *pPop,int nLength)
{
    if(pPush == NULL || pPop == NULL || nLength <=0)
    {
        return false;
    }
    stack<int>s;
    s.push(pPush[0]);
    int nPop_index = 0;
    int nPush_index = 1;
    while(nPop_index < nLength)
    {
        while(s.top() != pPop[nPop_index]&&nPush_index<nLength)
        {
            s.push(pPush[nPush_index]);
            nPush_index++;
        }
        if(s.top() == pPop[nPop_index])
        {
            s.pop();
            nPop_index++;
        }
        else
        {
            return false;
        }
    }
    return true;
}

int main(int argc,char *argv[]){
    
    int nPush[5] = {1,2,3,4,5};
    int nPop1[5] = {4,5,3,2,1};
    int nPop2[5] = {4,3,5,1,2};
    int nPop3[5] = {5,4,3,2,1};
    int nPop4[5] = {4,5,2,3,1};
    bool flag1 = false,flag2 = false;
    bool flag3 = false,flag4 = false;
    flag1 = IsPopOrder(nPush, nPop1, 5);
    if(flag1)
        cout<<"Pop1是压栈序列的弹出序列!"<<endl;
    else
        cout<<"Pop1不是压栈序列的弹出序列!"<<endl;
    flag2 = IsPopOrder(nPush, nPop2, 5);
    if(flag2)
        cout<<"Pop2是压栈序列的弹出序列!"<<endl;
    else
        cout<<"Pop2不是压栈序列的弹出序列!"<<endl;
    flag3 = IsPopOrder(nPush, nPop3, 5);
    if(flag3)
        cout<<"Pop3是压栈序列的弹出序列!"<<endl;
    else
        cout<<"Pop3不是压栈序列的弹出序列!"<<endl;
    flag4 = IsPopOrder(nPush, nPop4, 5);
    if(flag4)
        cout<<"Pop4是压栈序列的弹出序列!"<<endl;
    else
        cout<<"Pop4不是压栈序列的弹出序列!"<<endl;
    
    return 0;
}

4.运行效果:

Pop1是压栈序列的弹出序列!
Pop2不是压栈序列的弹出序列!
Pop3是压栈序列的弹出序列!
Pop4不是压栈序列的弹出序列!
Program ended with exit code: 0

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值