Stack push and pop Sequences

Source: Internet
Author: User

Question: enter two integer sequences. One sequence represents the push sequence of the stack and determines whether the other sequence may be in the pop sequence. For simplicity
See, we assume that any two integers of the push sequence are not equal.
For example, if the input push sequence is 1, 2, 3, 4, 5, 3, 2, and 1, it may be a pop series. Because there can be the following push and pop
Sequence: Push 1, Push 2, Push 3, Push 4, Pop, Push 5, pop, the resulting pop sequence is 4, 5,

3, 2, 1. However, sequences 4, 3, 5, 1, and 2 cannot be pop sequences of push sequences 1, 2, 3, 4, and 5.

Ideas:

When an auxiliary stack is introduced, an element of the push array is first imported into the stack. The elements at the top of the stack are compared with those at the current position of the POP array (position J starts from 0, and move the pop array one by one. If not, the elements at the current position of the push array (I starts from 0) will be added to the stack. Repeat the above steps until the stack is empty.

If I is greater than the size of the push array and J is smaller than the length of the POP array, the name is not matched; otherwise, the name is matched.


CodeImplementation:

Int ispoporder (int * Push, int * Pop, int Len) {If (push = NULL | Pop = NULL) // juge the arguement's validityreturn 0; int I = 0, j = 0; stack <int> s_push; s_push.push (push [I ++]); // push the first element to stackwhile (! S_push.empty () & I <= Len) {If (s_push.top () = pop [J]) {s_push.pop (); // pop stackj ++; // Add the position of the POP array} else {s_push.push (push [I ++]) ;}} if (I> Len & J <Len) return 0; return 1 ;}

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.