Implement Stack using Queues

Source: Internet
Author: User

1 classStack {2  Public:3     //Push element x onto stack.4     voidPushintx) {5         if(Q1.empty () &&q2.empty ())6 Q1.push (x);7         Else 8         {9             if(Q1.empty ())Ten Q2.push (x); One             ElseQ1.push (x); A         } -          -     } the  -     //removes the element on top of the stack. -     voidpop () { -          if(Q1.empty () &&q2.empty ()) +          return ; -          Else  +          { A              if(Q1.empty ()) at              { -                  if(q2.size () = =1) - Q2.pop (); -                  Else -                  { -                       while(Q2.size () >1) in                      { - Q1.push (Q2.front ()); to Q2.pop (); +                      } - Q2.pop (); the                  } *              } $              ElsePanax Notoginseng              { -                   if(q1.size () = =1) the Q1.pop (); +                  Else A                  { the                       while(Q1.size () >1) +                      { - Q2.push (Q1.front ()); $ Q1.pop (); $                      } - Q1.pop (); -                  } the              } -              }Wuyi          } the      -  Wu     //Get the top element. -     intTop () { About          if(Q1.empty () &&q2.empty ()) $          return-1; -          Else  -          { -              if(Q1.empty ()) A              { +                  returnQ2.back (); the              } -              Else $              { the                  returnQ1.back (); the              } the              } the          } -      in  the     //Return Whether the stack is empty. the     BOOLempty () { About         if(Q1.empty () &&q2.empty ()) the         return true; the         Else return false; the     } + Private: -queue<int>Q1; thequeue<int>Q2;Bayi};

Implement Stack using Queues

Related Article

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.