Stack eject, press-in sequence

Source: Internet
Author: User

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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.