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

来源:互联网 发布:amd表面格式优化 编辑:程序博客网 时间:2024/04/30 11:32

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