"Sword Point Offer" additional questions _ with two queues to implement a stack _c++ version

Source: Internet
Author: User

Tag:offer   coding    calculation    turn   actual    com    data structure     robustness    ==   

  In the "offer of sword", in the stack and queue exercises, the author left a topic for the reader to implement, that is, "two queues to implement a stack." In the computer data structure, the stack is characterized by a last-in, first-out, that is, the element that is pressed into the (push) stack will be ejected first (pop), the queue is characterized by FIFO, that is, the first element to enter the queue will be the first to bounce out.  Although the stack and queue characteristics are the opposite, but the two are interconnected, can be converted to each other. In the "implement a stack with two queues" problem, we use two queues to press in and bounce out to simulate the stack's press-in and eject.  We visualize abstract problems by means of drawing. In, we first press an element a into the stack. Since two queues are now empty, we can choose to insert a into any of the two queues. We might as well insert a into the queue1, and then continue to press into the B,C two elements in the net stack. We insert them all into the queue1.  This time queue1 contains 3 element A,b,c, where a is in the head of the queue and C is at the tail of the queue. Now let's consider popping an element from within the stack. According to the principle of the post-first out of the stack, the last C that is pressed into the stack should be ejected first. Since c is at the tail of queue1 and we can only delete elements from the head of the queue at a time, we can remove a, b from Queueu and insert it into queue2, and then remove C from queue1. This is equivalent to popping the element C from the stack.  We can pop the element b from the stack in the same way. Next we consider pressing an element d from within the stack. Now that queue1 has an element, we insert D into the tail of the queue1.  If we eject an element from the stack again, it should be the last to be pushed in the D. Since d is at the tail of queue1, we can only remove the queue1 element from the head and insert it into queue2 until Queue1 encounters D and deletes it directly. Note: In the above idea, two queues exist in the case of a full empty queue and an empty queue. Therefore, in the program to enter the first step of the child function, to determine whether the two queue is not empty (exception), increase the robustness of the program. In addition, empty stack delete element to report an exception, that is, two queues are empty; program updates in GitHub:  https://github.com/wylloong/tinyprograms/blob/master/coding%  20interviews/stackwithtwoqueues ************************************************************ C + + program implementation:
//face Question 9 Additional questions: Implementing stacks with two queues//title: Implement a stack with two queues. The declaration of the stack is as follows, please implement its two functions Appendtail//and Deletehead, respectively, complete the insertion of nodes at the end of the stack and delete nodes in the stack head function. #pragmaOnce#include<queue>#include<exception>using namespacestd;template<typename t>classcstack{ Public: Cstack (); ~Cstack (); voidAppendtail (Constt&node); T Deletehead ();Private: Queue<T>queue1; Queue<T>queue2;}; Template<typename t> cstack<t>:: Cstack () {}template<typename t> cstack<t>::~Cstack () {}//inserting elementsTemplate<typename t>voidCstack<t>::appendtail (Constt&node) {    if(Queue1.size () >0&& queue2.size () >0)    {        //Abnormal conditions    }    Else    {        //insert into non-empty queue, if both are empty insert into queue2        if(queue1.size () = =0) {Queue2.push (node); }        Else{Queue1.push (node); }}}template<typename t> T cstack<t>::d eletehead () {if(queue1.size () = =0&& queue2.size () = =0)    {        //Abnormal conditions        Throw Newexception"stack is empty");    } T head; if(Queue1.size () >0)    {         while(Queue1.size () >1)        {            //the elements in Queue1 are deleted in turn and inserted into Queue2, where queue1 removes the last element//is equivalent to popping the tail element from the stack .T& data =Queue1.front ();            Queue1.pop ();        Queue2.push (data); } head=Queue1.front ();    Queue1.pop (); }    Else    {         while(Queue2.size () >1)        {            //the elements in Queue2 are deleted in turn and inserted into queue1, where queue2 removes the last element//is equivalent to popping the tail element from the stack .T& data =Queue2.front ();            Queue2.pop ();        Queue1.push (data); } head=Queue2.front ();    Queue2.pop (); }    returnhead;}
#include"CStacks.h"//==================== test Code ====================voidTestCharActualCharexpected) {    if(Actual = =expected) printf ("Test passed.\n"); Elseprintf ("Test failed.\n");}intMainintargcChar*argv[]) {    //Last in, first outcstack<Char>Stack; Stack.appendtail ('a'); Stack.appendtail ('b'); Stack.appendtail ('C'); CharHead =Stack.deletehead (); Test (head,'C'); Head=Stack.deletehead (); Test (head,'b'); Stack.appendtail ('D'); Head=Stack.deletehead (); Test (head,'D'); Stack.appendtail ('e'); Head=Stack.deletehead (); Test (head,'e'); Head=Stack.deletehead (); Test (head,'a'); //empty stack Delete, triggering exception//head = Stack.deletehead ();GetChar (); return 0;}

"Sword Point Offer" additional questions _ with two queues to implement a stack _c++ version

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.