You are viewing a single comment's thread. Return to all comments →
I did it even more effecient, it's not needed to copy full stack all the time. Since, you could remove some of them without printing:
#include <stack> using namespace std; int main() { std::stack<int> left; std::stack<int> right; int q; std::cin >> q; int elems_to_copy = 0; for (;q > 0; --q) { int action; std::cin >> action; switch(action) { case 1: int val; std::cin >> val; right.push(val); ++elems_to_copy; break; case 2: if (!left.empty()) { left.pop(); } else { --elems_to_copy; } break; case 3: if (left.empty()) { /* Partially move the stack */ for (int i = 0; i < elems_to_copy; ++i) { left.push(right.top()); right.pop(); } elems_to_copy = 0; } std::cout << left.top() << std::endl; break; } } return 0; }
Seems like cookies are disabled on this browser, please enable them to open this website
Queue using Two Stacks
You are viewing a single comment's thread. Return to all comments →
I did it even more effecient, it's not needed to copy full stack all the time. Since, you could remove some of them without printing: