A stack can be implemented using two queues.
Method 1 (By making push operation costly)
This method makes sure that newly entered element is always at the front of ‘q1′, so that pop operation just dequeues from ‘q1′. ‘q2′ is used to put every new element at front of ‘q1′.
This method makes sure that newly entered element is always at the front of ‘q1′, so that pop operation just dequeues from ‘q1′. ‘q2′ is used to put every new element at front of ‘q1′.
push(s, x) // x is the element to be pushed and s is stack
1) Enqueue x to q2
2) One by one dequeue everything from q1 and enqueue to q2.
3) Swap the names of q1 and q2
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1.
pop(s)
1) Dequeue an item from q1 and return it.
Method 2 (By making pop operation costly)
In push operation, the new element is always enqueued to q1. In pop() operation, if q2 is empty then all the elements except the last, are moved to q2. Finally the last element is dequeued from q1 and returned.
In push operation, the new element is always enqueued to q1. In pop() operation, if q2 is empty then all the elements except the last, are moved to q2. Finally the last element is dequeued from q1 and returned.
push(s, x)
1) Enqueue x to q1 (assuming size of q1 is unlimited).
pop(s)
1) One by one dequeue everything except the last element from q1 and enqueue to q2.
2) Dequeue the last item of q1, the dequeued item is result, store it.
3) Swap the names of q1 and q2
4) Return the item stored in step 2.
// Swapping of names is done to avoid one more movement of all elements
// from q2 to q1.
http://shibaili.blogspot.com/2015/06/day-112-count-complete-tree-nodes.html用queue的大小来控制倒腾,只用一个queue,而不是两个
public: // Push element x onto stack. void push(int x) { topElem = x; q.push(x); } // Removes the element on top of the stack. void pop() { for (int i = 0; i < q.size() - 1; i++) { topElem = q.front(); q.push(q.front()); q.pop(); } q.pop(); } // Get the top element. int top() { return topElem; } // Return whether the stack is empty. bool empty() { return q.empty(); }private: queue<int> q; int topElem;};public class _06_MyStack<T> { private Queue<T> q1 = new LinkedList<T>(); private Queue<T> q2 = new LinkedList<T>(); public void push(T item){ if(!q1.isEmpty()){ q1.add(item); }else{ q2.add(item); } } public T pop(){ if(q1.isEmpty()){ while(q2.size()>1){ q1.add(q2.poll()); } return q2.poll(); }else{ while(q1.size()>1){ q2.add(q1.poll()); } return q1.poll(); } } public T peek(){ T tmp = null; if(q1.isEmpty()){ while(q2.size()>1) q1.add(q2.poll()); if(q2.size() == 1){ tmp = q2.peek(); q1.add(q2.poll()); } }else if(q2.isEmpty()){ while(q1.size()>1) q2.add(q1.poll()); if(q1.size() == 0){ tmp = q1.peek(); q2.add(q1.poll()); } } return tmp; } public int size(){ return q1.size() + q2.size(); }}Read full article from Implement Stack using Queues | GeeksforGeeks