using the characteristics of the stack to implement the queue
1. Stack-last in first out, queue-FIFO, use two stacks, stack 1 for push data, stack 2 as pop data.
2. Principle Analysis:
1). Push data-when the simulated implementation of the queue push data is pushed in stack 1.
2). Pop data-determine if stack 2 is empty, if stack 2 is empty, then the stack 1 data is first pressed into Stack 2 (take the top element of the stack to push to stack 2), and then the stack top element of the pop stack 2. If, stack 2 has elements, the stack top element of the direct pop stack 2.
3). Printing elements
A: Stack 1 and Stack 2 have no elements--return directly.
B: Stack 1 has elements and stack 2 has no elements--push the elements of stack 1 to stack 2, then print the elements of stack 2 sequentially.
C: Stack 1 has no elements and the stack 2 has elements--print directly the elements of stack 2.
D: stack 1 has elements and the stack 2 has elements--first print the stack 2 elements (pop off each element of printing), then push the elements of the stack 1 to stack 2, then print the elements of stack 2 sequentially.
class queue //is using stacks in the library { public: void push (Const int &&NBSP;X) { _st1.push (x); } void pop () { if (_st1.empty () && _st2.empty ()) { cout << "empty queue!" << endl; return; } if (!_st2.empty ()) { _st2.pop (); } else { while (!_st1.empty ()) { _st2.push (_st1. Top ()); _st1.pop (); } _st2.pop (); } } void print () { stack<int> tmp1 = _st1; //not have these two sentences will be out bug stack<int> tmp2 = _st2; if (_st1.empty () && _st2.empty ()) //stack 1 and Stack 2 have no elements { cout << "empty queue! " << endl; return; } else if ((!_st1.empty ()) && _st2.empty ()) //stack 1 has elements and stack 2 has no elements { while (!tmp1.empty ()) { tmp2.push (Tmp1.top ()); tmp1.pop (); } while (!tmp2.empty ()) { cout << tmp2.top () << tmp2.pop (); } cout << endl; } else if (_st1.empty () && (!_st2.empty () ) //Stack 1 has no elements and stack 2 has elements { while (! Tmp2.empty ()) { cout << tmp2.top () << endl; tmp2.pop (); } } else if ((!tmp1.empty ()) && (!tmp2.empty ())) // Stack 1 has elements and stack 2 has elements &nBsp { while (!tmp2.empty ()) { cout << tmp2.top () << endl; tmp2.pop (); } while (!tmp1.empty ()) { tmp2.push (Tmp1.top ()); tmp1.pop (); } while (!tmp2.empty ()) { cout << tmp2.top () << endl; tmp2.pop (); } } } private: stack<int> _st1; //Stack 1 stack<int> _st2; //Stack 2 };
The above is my study in the process of some experience summary. Of course, my ability is limited, there will inevitably be flaws, I hope you can correct me.
This article is from the "make a small driver" blog, please be sure to keep this source http://10799170.blog.51cto.com/10789170/1763146
Two stacks to implement a queue