Implement queue effects using stacks
Use two stacks to implement the queue effect. You can import the stack, output the stack, and judge the empty space...
Basic stack Functions
Lstack. h
# Ifndef _ LSTACK_H # define _ LSTACK_H # include
Using namespace std; // Stack class Stack {public: // empty Stack (void): m_top (NULL) initialized during the construction process) {}// destroy the remaining nodes during the Destructor ~ Stack (void) {for (Node * next; m_top = next) {next = m_top-> m_next; delete m_top ;}// press void push (int data) {/* Node * node = new Node; node-> m_data = data; node-> m_next = m_top; m_top = node; */m_top = new Node (data, m_top) ;}// int pop (void) {if (empty () throw UnderFlow (); int data = m_top-> m_data; node * next = m_top-> m_next; delete m_top; m_top = next; return data;} // empty bool empty (void) const {Return! M_top;} private: // UnderFlow exception class UnderFlow: public exception {const char * what (void) const throw () {return "Stack UnderFlow! ";}}; // Node class Node {public: Node (int data = 0, Node * next = NULL): m_data (data), m_next (next) {} int m_data; // data Node * m_next; // post pointer}; Node * m_top; // stack top}; # endif // _ LSTACK_H
Implemented queue:
Squeue. cpp
# Include
# Include "lstack. h "using namespace std; // stack-based Queue class Queue {public: // press void push (int data) {m_ I .push (data );} // The int pop (void) {if (m_o.empty () {if (m_ I .empty () throw underflow_error ("queue overflow! "); While (! M_ I .empty () m_o.push (m_ I .pop ();} return m_o.pop ();} // empty bool empty (void) const {return m_ I .empty () & m_o.empty ();} private: Stack m_ I; // input Stack m_o; // output Stack}; int main (void) {try {Queue queue; for (int I = 0; I <10; ++ I) queue. push (I); cout <queue. pop () <endl; // 0 cout <queue. pop () <endl; // 1 cout <queue. pop () <endl; // 2 cout <queue. pop () <endl; // 3 cout <queue. pop () <Endl; // 4queue. push (10); queue. push (11); queue. push (12); while (! Queue. empty () cout <queue. pop () <endl;} catch (exception & ex) {cout <ex. what () <endl; return-1;} return 0 ;}