#include <iostream> #include <assert.h> #include <queue> using namespace std; /* Two queues simulate a stack */* queue A, B into the stack: the element is pressed into a non-empty queue, the first element is overwhelming to the column a stack: Pour the first n-1 element of queue A to queue B, remove the nth element. At this point the data is in B, and the next action is done for B. Stack top: N-1 The first element of queue A to queue B, the nth element as the top of the stack */template <typename t> class Mystack {public://In the stack, the first element into the queue deque1, each element later into a non-empty queue void push (const T &element); Out of the stack, the first n-1 elements of the non-empty queue are transferred to another empty queue, and the nth element of the non-empty queue is deleted void pop (); The top element of the stack, transferring the first n-1 elements of a non-empty queue to another empty queue, returning the nth element of a non-empty queue to T top (); Whether the stack is empty bool empty () {return (Q1.empty () &&q2.empty ()); } private:queue<t> Q1; Queue<t> Q2; }; Template<typename t> void Mystack<t>::p ush (const T &element) {if (Q1.empty () && q2.empty ()) {Q 1.push (Element); } else if (!q1.empty () && q2.empty ()) {Q1.push (element); } else if (Q1.empty () &&!q2.empty ()) {Q2.push (element); }} template<typename t>void Mystack<t>::p op () {if (!q1.empty ()) {int size = Q1.size (); for (int i=0; i<size-1; i++) {Q2.push (Q1.front ()); Q1.pop (); } q1.pop (); } else {int size = Q2.size (); for (int i=0; i<size-1; i++) {Q1.push (Q2.front ()); Q2.pop (); } q2.pop (); }} template <typename t>t mystack<t>::top () {if (!q1.empty ()) {int size = Q1.size (); for (int i=0; i<size-1; i++) {Q2.push (Q1.front ()); Q1.pop (); } T temp = Q1.front (); Q1.pop (); Q2.push (temp); return temp; } else {int size = Q2.size (); for (int i=0; i<size-1; i++) {Q1.push (Q2.front ()); Q2.pop (); } T temp = Q2.front (); Q2.pop (); Q1.push (temp); return temp; }} int main (int argc, char *argv[]) {mystack<int> my; for (int i=0; i<10; i++) {My.push (i); } while (!my.empty ()) {cout<<my.top () << ""; My.pop (); } cout<<endl; return 0;}
Two queues to simulate a stack