class MyStack { public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { q.push(x); } /** Removes the element on top of the stack and returns that element. */ int pop() { int val; while(q.size() != 1) { int x = q.front(); h.push(x); q.pop(); } val = q.front(); // h.push(x); q.pop(); while(h.size()) { int x = h.front(); h.pop(); q.push(x); } return val; } /** Get the top element. */ int top() { int val; while(q.size() != 1) { int x = q.front(); h.push(x); q.pop(); } val = q.front(); h.push(val); q.pop(); while(h.size()) { int x = h.front(); h.pop(); q.push(x); } return val; } /** Returns whether the stack is empty. */ bool empty() { return q.size() == 0; } private: queue<int> q, h; };
Accepted
16/16 cases passed (8 ms)
Your runtime beats 6.14 % of cpp submissions
Your memory usage beats 5.42 % of cpp submissions (9.1 MB)