Data structure and algorithm stack and queue two: Stack push-in, pop-up sequence

Source: Internet
Author: User

At that time I was learning this is also very do not understand this problem, a stack of indentation and pop-up sequence of the judgment of a look not to know, but also to determine what to do. As long as the last-in-first-out rule is met. But here's what I'm going to say briefly about this press-in and pop-up sequence. Is the two sequence we have given the hypothesis, one for the press-in sequence and one for the pop-up sequence. Then we go through an auxiliary stack, pushing the data into the sequence into a temporary secondary stack, if the top element of the stack is just like the data from the pop-up sequence, then we pop up, and if not, we'll press the data in the sequence into the temporary stack until we get to the end of the sequence. If the press-in sequence ends, all data pops up on the temporary stack, which is a popup press-in or pop-up sequence. Directly understand:

The code is as follows:

 Public BooleanIspoporder (intArr1[],intarr2[]) {    //determine if two sequences have an empty sequence    if(Arr1.length = = 0 | | arr2.length = = 0){          return false; }    //Create a temporary secondary stackstack<integer> s =NewStack<>(); //press the data into the stack and compare it     for(inti = 0,j = 0;i <arr1.length;) {S.push (arr1[i]); //determines whether the top element of the stack matches the pop-up sequence          while(S.size () > 0 && s.peek () = =Arr2[j])              {S.pop (); J++; }    }    returns.isempty ();}

The code above me uses an array to implement the sequence. ARR1 represents a press-in sequence, and arr2 represents a pop-up sequence. The key thing we need to catch is the pop-up comparison on the loop at the press-in, with the help of a temporary stack to implement the algorithm.

Data structure and algorithm stack and queue two: Stack push-in, pop-up 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.