Use two stacks to implement queues and two stacks to implement queues
Question: Use two stacks to implement a queue. The queue declaration is as follows. Implement the appendTail and deleteHead functions to insert nodes at the end of the queue and delete nodes at the queue header respectively.
template <typename T>class CQueue{public: CQueue(void); ~CQueue(void); void appendtail(const T& node); T deleteHead();private: stack<T> stack1; stack<T> stack2;};
Solution:
The insert operation is performed in stack1, And the delete operation is performed in stack2. If stack2 is empty, all elements in stack1 are transferred to stack2.
# Include <stack> # include <stdio. h> # include <iostream> using namespace std; template <typename T> class CQueue {public: CQueue (void );~ CQueue (void); void appendTail (const T & node); T deleteHead (); private: stack <T> stack1; stack <T> stack2 ;}; // constructor template <typename T> CQueue <T>: CQueue (void) {}// destructor template <typename T> CQueue <T> ::~ CQueue (void) {}// Insert the element template <typename T> void CQueue <T >:: appendTail (const T & element) {stack1.push (element );} // Delete the element and return the template <typename T> T CQueue <T>: deleteHead () {if (stack2.size () <= 0) // when stack2 is empty, the number in stack1 can be moved over {while (stack1.size ()> 0) {T & data = stack1.top (); stack1.pop (); stack2.push (data) ;}} if (stack2.size () = 0) // throw new exception ("queue is empty"); exit (1 ); T head = stack2.top (); stack2.pop (); return head;} void Test (char actual, char expected) {if (actual = expected) printf ("Test passed \ n"); else printf ("Test failed. \ n ");} int main () {CQueue <char> queue; queue. appendTail ('A'); queue. appendTail ('B'); queue. appendTail ('C'); char head = 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'); int length = 4; while (length> 0) {printf ("% c", queue. deleteHead (); -- length;} return 0 ;}