#include <iostream> #include <stack> using namespace std; class QueueUsingStacks { private: stack<int> enqueueStack; stack<int> dequeueStack; void transferToDequeueStack() { // Move elements from enqueueStack to dequeueStack while (!enqueueStack.empty()) { dequeueStack.push(enqueueStack.top()); enqueueStack.pop(); } } public: void put(int value) { enqueueStack.push(value); } void pop() { if (dequeueStack.empty()) { transferToDequeueStack(); } if (!dequeueStack.empty()) { dequeueStack.pop(); } } int peek() { if (dequeueStack.empty()) { transferToDequeueStack(); } return dequeueStack.top(); } }; int main() { int q; cin >> q; QueueUsingStacks queue; for (int i = 0; i < q; ++i) { int queryType; cin >> queryType; if (queryType == 1) { int value; cin >> value; queue.put(value); } else if (queryType == 2) { queue.pop(); } else if (queryType == 3) { cout << queue.peek() << endl; } } return 0; }
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter