Stack push-in, pop-up sequence

Source: Internet
Author: User

Title Description

Enter a sequence of two integers, and the first sequence represents the stacking order of the stack, judging whether the second sequence is the pop-up order for 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.


Solution:

Operation of the simulation stack

Create a stack variable that represents the stack;


  1. If the stack is empty, or stack.top () ==popv[i],stack.pop

  2. Otherwise, Stack.push (PUSHV "Inpos])


  3.  bool IsPopOrder(vector<int> pushV, vector<int> popV) {
  4. int size1 = Pushv.size ();
  5. int size2 = Popv.size ();
  6.     if (size1 != size2||size1==0)
  7.         return false;
  8.     stack<int> st;
  9.     int inpos = 0;
  10.     for (int i = 0; i<size2;) {
  11. if (!st.empty () && st.top () = = Popv[i]) {
  12. st.pop ();
  13. i++;
  14. }
  15. else {
  16. if (Inpos < size1)
  17. st.push (pushv[inpos++]);
  18.             else
  19.                 return false;
  20. }
  21. }
  22. return inpos = = Size1&&st.empty ();
  23. }

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.