Title: Implement a queue with two stacks. The declaration of the queue is as follows, implementing its two functions Appendtail and Deletehead, respectively, to complete the function of inserting nodes at the end of the queue and deleting nodes at the head of the queue.
Template <typename t>class cqueue{public: Cqueue (void); ~cqueue (void); void appendtail (const t& node); T Deletehead (); Private : Stack<T> stack1; Stack<T> stack2;};
Problem Solving Ideas:
The insert operation is performed in Stack1, the delete operation is performed in Stack2, and if the Stack2 is empty, all elements in the stack1 are transferred to Stack2.
#include <stack>#include<stdio.h>#include<iostream>using namespacestd;template<typename t>classcqueue{ Public: Cqueue (void); ~cqueue (void); voidAppendtail (Constt&node); T Deletehead ();Private: Stack<T>Stack1; Stack<T>Stack2;};//constructor FunctionTemplate <typename t> Cqueue<t>::cqueue (void){}// DestructorsTemplate <typename t> Cqueue<t>::~cqueue (void){}//inserting elementsTemplate <typename t>voidCqueue<t>::appendtail (Constt&Element) {Stack1.push (element);}//Delete the element and returnTemplate <typename t> T cqueue<t>::d eletehead () {if(Stack2.size () <=0) //You can move the number in Stack1 when Stack2 is empty . { while(Stack1.size () >0) {T& data =Stack1.top (); Stack1.pop (); Stack2.push (data); } } if(stack2.size () = =0) //throw new Exception ("Queue is empty");Exit1); T Head=Stack2.top (); Stack2.pop (); returnhead;}voidTest (CharActualCharexpected) { if(Actual = =expected) printf ("Test passed\n"); Elseprintf ("Test failed.\n");}intMain () {Cqueue<Char>queue; Queue.appendtail ('a'); Queue.appendtail ('b'); Queue.appendtail ('C'); CharHead =Queue.deletehead (); Test (Head,'a'); Head=Queue.deletehead (); Test (Head,'b'); Queue.appendtail ('D'); Head=Queue.deletehead (); Test (Head,'C'); Queue.appendtail ('e'); Head=Queue.deletehead (); Test (Head,'D'); Head=Queue.deletehead (); Test (Head,'e'); Queue.appendtail ('a'); Queue.appendtail ('b'); Queue.appendtail ('C'); Queue.appendtail ('D'); intLength =4; while(Length >0) {printf ("%c", Queue.deletehead ()); --length; } return 0;}
Using two stacks to implement a queue