Title: Determine whether a number sequence is a way of stacking these numbers into the stack
Ideas:
First of all to apply for a secondary stack to simulate the stack, and then determine whether the stack top element and the stack number is consistent, inconsistent then into the stack sequence sequentially into the stack, until the top of the stack and the stack number consistent: Pop up the stack top element, the stack sequence of the pointer after the stack, when the last digit into the stack and it does not Proof that the pop-up sequence is incorrect.
The code is as follows:
#include <iostream>#include<stack>using namespacestd;BOOLIsorder (Const int*push,Const int* Pop,intlength) { if(Push!=null && pop!=null && length>0) { BOOLresult=false; Const int*newpush=push; Const int*newpop=Pop; Stack<int>data; while(newpop-pop<length) { //if the stack is empty or the top of the stack is not equal to the number to eject, the stack if(data.size () = =0|| *newpop!=Data.top ()) {Data.push (*Newpush); Newpush++; //The last number is already in the stack . if(newpush-push>=length) { //If the top of the stack is not equal to the number to eject, and the last number is already in the stack, it proves that it is not a stack sequence if(*newpop!=data.top ()) Break; } } Else{ //If the number you want to eject matches the top element of the stack, the stack pops upData.pop (); Newpop++; } } //if the stack is empty and the pop-up sequence reaches the end, it proves to be the stack sequence if(Newpop-pop==length && data.size () = =0) Result=true; returnresult; }}
Test the code and run the results:
int main ()
{
int a[5]={1,2,3,4,5};
int b[5]={4,5,3,2,1};
int c[5]={4,3,5,1,2};
Cout<<isorder (a,b,5) <<endl;
Cout<<isorder (a,c,5) <<endl;
return 0;
}
Stack eject, press-in sequence