栈的压入弹出序列

首先来看图,来看下压入顺序是1、2、3、4、5.弹出顺序是4、5、3、2、1
的情况下的栈的顺序:

是这样没错。怎么来的呢?
我们结合压入和弹出的数组来考虑。
首先我看弹出的数组:
为什么4在最开始处呢?压入顺序是:
说明这个栈里己经有了1、2、3、4

于是我们弹出4。

现在弹出顺出数组里指向了5

现在我们栈里没有5啊?哪来的5。于是我们先压入5.

再弹出5

于是看我们的弹出数组现在指向了3

我们栈里第一个就是3,那么弹出3

同样我们弹出2,然后弹出1

现在栈变为空了。
其实上面我们采用了逆向思维的方式,我们从弹出的数组顺序中开始推测以前的压入顺序,倒过来模拟以前的那个栈的工作过程。
如果模拟过程中压入的数字正好和我们弹出的数组相配套,那么最后栈定是空的,否则就不为空嘛。
源代码:
#ifndef IS_STACK_SEQ_H#define IS_STACK_SEQ_H#include<stack>#include<iostream>bool isStackSeq(int *arrPush,int *arrPop,int Length){if(arrPush==NULL||arrPop==NULL||Length==0){throw("invalid input ");return false;}std::stack<int> stack_pop;std::stack<int> stack_push;for(int i=0;i<Length; i++){stack_pop.push(arrPop[i]);}int *arrPushEnd=arrPush+Length-1;while(arrPush<=arrPushEnd){while(*arrPush!=stack_pop.top()){stack_push.push(*arrPush);arrPush++;}arrPush++;stack_pop.pop();}while(stack_push.size()!=0){if(stack_pop.top()!=stack_push.top()){return false;}else{stack_pop.pop();stack_push.pop();}}return true;}#endif
测式:
#include"isTheStackSeq.h"#include<iostream>int main(){int push[5]={1,2,3,4,5};int pop[5]={5,4,3,2,1};std::cout<<isStackSeq(push,pop,5);}
浙公网安备 33010602011771号