Written question: Implementing a queue with two stacks

Source: Internet
Author: User

#include <iostream>#include <stack>using namespace STD;Template<TypeNameT>classqueue{ Public: QUEUE () {} ~queue () {}voidAPPEND (ConstT val) { while(St2.empty () = =false)        {//We only use ST2 to save the data, St1 as the intermediate Exchange Bridge.         //First save the data in St2 in reverse order in ST1. St1.push (St2.top ());        St2.pop (); }//Then place the input value at the top of the st1. St1.push (Val); while(St1.empty () = =false)        {The data in St1 is now all put in St2,            //Exactly guaranteed that the new Val was at the bottom and realized the            //Queue advanced after the idea. St2.push (St1.top ());        St1.pop (); }    }intDelhed () {inttemp = St2.top (); St2.pop ();returnTemp }voidPrintf () { Stack<int>ST3 = St2;//print, in order to not affect the original stack, choose to use a temporary variable.          while(St3.empty () = =false)        {cout<<st3.top () <<"  ";        St3.pop (); }cout<<endl; }Private: Stack<T>ST1; Stack<T>St2;};intMain () {queue<int> QE; for(intI=0;i<Ten; i++) {QE.           APPEND (i); } QE.    Printf (); Sel    Delhed (); Sel    Printf (); Sel    Delhed (); Sel    Printf (); Sel    Delhed (); Sel    Printf (); Sel    Delhed (); Sel    Printf (); Sel    Delhed (); Sel    Printf (); Sel    Delhed (); Sel    Printf (); Sel    Delhed (); Sel Printf ();return 0;}

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Written question: Implementing a queue with two stacks

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.