面试题22栈的压入弹出序列

来源:互联网 发布:淘宝举报中心网址 编辑:程序博客网 时间:2024/06/03 16:08

剑指offer-面试题22.栈的压入,弹出序列

题目:输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1、2、3、4、5是某栈的压栈序列,序列4、5、3、2、1是该压栈序列对应的一个弹出序列,但4、3、5、1、2就不可能是该该压栈序列的弹出序列。

本题的题解步骤如下:

1.设置一个辅助栈S,用于模拟出栈入栈顺序,设入栈顺序序列为pPush,出栈顺序序列为pPop

2.设置两个索引或指针分别指向入栈序列和出栈序列的第一个元素

3.顺序索引入栈元素,当入栈元素不等于出栈元素的时候,将入栈元素依次压入辅助栈S

4.当两者相等的时候,压入该元素到辅助栈S中同时将栈顶元素出栈,出栈入栈序列的索引均向后移动一个位置

5.当入栈序列索引结束之后,pPush剩余的元素全部已压入栈S

6.依次索引pPop如果pPop与辅助栈顶元素比较如果相等这将辅助栈顶弹出

7.当栈中所有的元素均弹出的时候则说明出栈顺序序列与正好是入栈顺序序列对应的出栈顺序。否则出栈顺序与入栈顺序不匹配

#include<iostream>#include<stack>using namespace std;//pPush插入队列的顺序//pPop弹出的顺序//length   pPush的长度bool IsPop(const int *pPush,const int *pPop,int length){bool possible=false;if(pPush!=NULL&&pPop!=NULL&&length>0){const int* nextpush=pPush;const int* nextpop=pPop;std::stack<int>data;while(nextpop-pPop<length){while(data.empty()||data.top()!=*nextpop){if(nextpush-pPush==length)break;data.push(*nextpush);nextpush++;}if(data.top()!=*nextpop)break;data.pop();nextpop++;}if(data.empty() && nextpop-pPop==length)possible=true;}return possible;}void Test(char *testName,const int* pPush,const int*pPop,int nLength,bool expected){if(testName!=NULL)printf("%s begin: ",testName);if(IsPop(pPush,pPop,nLength)==expected)printf("passed\n");elseprintf("failed\n");}  void Test1()  {      const int nLength = 5;      int push[nLength] = {1, 2, 3, 4, 5};      int pop[nLength] = {4, 5, 3, 2, 1};            Test("Test1", push, pop, nLength, true);  }    void Test2()  {      const int nLength = 5;      int push[nLength] = {1, 2, 3, 4, 5};      int pop[nLength] = {3, 5, 4, 2, 1};            Test("Test2", push, pop, nLength, true);  }  void Test3()  {      const int nLength = 5;      int push[nLength] = {1, 2, 3, 4, 5};      int pop[nLength] = {4, 3, 5, 1, 2};            Test("Test3", push, pop, nLength, false);  }    void Test4()  {      const int nLength = 5;      int push[nLength] = {1, 2, 3, 4, 5};      int pop[nLength] = {3, 5, 4, 1, 2};            Test("Test4", push, pop, nLength, false);  }    // push和pop序列只有一个数字  void Test5()  {      const int nLength = 1;      int push[nLength] = {1};      int pop[nLength] = {2};        Test("Test5", push, pop, nLength, false);  }    void Test6()  {      const int nLength = 1;      int push[nLength] = {1};      int pop[nLength] = {1};        Test("Test6", push, pop, nLength, true);  }    void Test7()  {      Test("Test7", NULL, NULL, 0, false);  }     int main()  {      Test1();      Test2();      Test3();      Test4();      Test5();      Test6();      Test7();      system("pause");    return 0;  }  


原创粉丝点击