You must use only standard operations of a queue —— which means only push to back, peek/pop from front, size and is empty operations are valid.
Depending on your language, queue may not be supported natively. You may simulate a queue by using a list or deque(double-ended que), as long as you use only standard operations of a queue.
You may assume that all operations are valid(eg. no pop or top operations will be called on an empty stack).
class Stack { private: queue<int> queue1; queue<int> queue2; public: // Push element x onto stack. voidpush(int x){ if (queue1.empty()) { queue1.push(x); while(!queue2.empty()) { int tmp = queue2.front(); queue2.pop(); queue1.push(tmp); } } else { queue2.push(x); while(!queue1.empty()) { int tmp = queue1.front(); queue1.pop(); queue2.push(tmp); } } } // Removes the element on top of the stack. voidpop(){ if (!queue1.empty()) queue1.pop(); if (!queue2.empty()) queue2.pop(); } // Get the top element. inttop(){ if (!queue1.empty()) return queue1.front(); if (!queue2.empty()) return queue2.front(); return0; } // Return whether the stack is empty. boolempty(){ return queue1.empty() && queue2.empty(); } };
class Stack { private: queue<int> q1; public: // Push element x onto stack. voidpush(int x){ q1.push(x); int size = q1.size(); int pushTemp; while (size > 1) { pushTemp = q1.front(); q1.pop(); q1.push(pushTemp); size--; } } // Removes the element on top of the stack. voidpop(){ q1.pop(); } // Get the top element. inttop(){ return q1.front(); } // Return whether the stack is empty. boolempty(){ return q1.empty(); } };