Stacks and queues are two data structures with opposite characteristics, but are very closely related.
The feature of the stack is "LIFO", that is, the stack element that was last pushed (pushed) will be ejected first (pop).
The queue is characterized by "FIFO first", that is, the first element to enter the queue will be first ejected. In the tree width first traversal algorithm, we are traversing a certain layer of tree nodes, the nodes of the node in a queue, in order to the next layer of node traversal.
Interview question 7: Implement queues with two stacks
Topic: Implement a queue with two stacks. The queue is declared as follows, implement its two functions Appendtail and deletehead, complete the function of inserting a node at the end of the queue and deleting the node in the queue header respectively.
#include <stack> #include <queue> #include <exception> #include <iostream> using namespace std;
Template <typename t> class Cqueue {public:cqueue (void);
~cqueue (void);
Add a node void Appendtail (const t& node) at the end of the queue;
Deletes a queue's head node T deletehead ();
Private:stack<t> Stack1;
Stack<t> Stack2;
}; Template <typename t> cqueue<t>::cqueue (void) {} template <typename t> cqueue<t>::~cqueue (void
{} template <typename t> void cqueue<t>::appendtail (const t& node) {Stack1.push (node);}
Template <typename t> T cqueue<t>::d Eletehead () {if (Stack2.size () <=0) {while (Stack1.size () >0)
{T Tempnode = Stack1.top ();
Stack1.pop ();
Stack2.push (Tempnode);
} if (Stack2.size () ==0) {throw new Exception ("Queue is empty");
} T head = Stack2.top ();
Stack2.pop ();
return head;
} template <typename t> class Cstack {public:cstack (void);
~cstack (void);Add a node void Appendtail (const t& node) at the end of the queue;
Delete head node T deletehead ();
Private:queue queue1;
Queue queue2;
}; Template <typename t> cstack<t>::cstack (void) {} template <typename t> cstack<t>::~cstack (void
{} template <typename t> void cstack<t>::appendtail (const t& node) {Queue1.push (node);}
Template <typename t> T cstack<t>::d Eletehead () {if (Queue2.size () <=0) {while (Queue1.size () >0)
{T temp = Queue1.front ();
Queue1.pop ();
Queue2.push (temp);
} if (queue2.size () = = 0) {Throw new Exception ("Queue is empty");
} T head = Queue2.front ();
Queue2.pop ();
return head; }
1, focus on the stack and the understanding of the queue;
2, the ability to write code related to the template;
3, the ability to analyze complex problems. Learn to visualize problems by drawing.