Stack push-in, pop-up sequence

Source: Internet
Author: User

Source: Niu ke net "jian refers to offer"

The title description input two integer sequence, the first sequence represents the stack's indentation order, determine whether the second sequence is the pop-up order of the stack. Assume that all the numbers that are pressed into the stack are not equal. For example, the sequence 1,2,3,4,5 is the indentation order of a stack, and the sequence 4,5,3,2,1 is a pop-up sequence corresponding to the stack sequence, but 4,3,5,1,2 is not likely to be the pop-up sequence of the stack sequence. (Note: The lengths of the two sequences are equal)

pusha={1,2,3,4,5}

popa={4,5,3,1,2}

popb={4,3,5,1,2}

First look at Popa, the first is 4, so you need to 1,2,3,4 all into the stack, and then pop up 4, at this time top=3. The next one is 5, not the top, so you need to put the next element in the Pusha into the stack, and then compare whether the new is equal to 5. If it is equal, the stack will be out, and if not, continue to stack the numbers from Pusha. The termination condition is that the stack is empty or the Pusha array traversal is complete.

1  Public BooleanIspoporder (int[] Pusha,int[] PopA) {2         if(pusha.length==0 | | popa.length==0)return false;3         if(pusha.length!=popa.length)return false;4 5stack<integer> stack =NewStack<integer>();6Stack.push (Pusha[0]);//autoboxing7 8          for(intI=1, j=0; ;){9             if(Stack.empty ())return true;Ten             if(!stack.empty () && Stack.peek ()!=popa[j]) {//Unboxing One                 if(i==pusha.length) Break; A Stack.push (Pusha[i]); -i++; -}Else if(!stack.empty () && stack.peek () = =Popa[j]) { the Stack.pop (); -J + +; -             } -         } +  -         return false; +}

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.