用两个队列实现栈
class MyStack { private: queue<int> q1, q2; public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { q1.push(x); } /** Removes the element on top of the stack and returns that element. */ int pop() { int num = 0; while (!q1.empty()) { if (q1.front() == q1.back()) { num = q1.front(); q1.pop(); continue; } q2.push(q1.front()); q1.pop(); } while (!q2.empty()) { q1.push(q2.front()); q2.pop(); } return num; } /** Get the top element. */ int top() { int num = 0; while (!q1.empty()) { if (q1.front() == q1.back()) { num = q1.front(); } q2.push(q1.front()); q1.pop(); } while (!q2.empty()) { q1.push(q2.front()); q2.pop(); } return num; } /** Returns whether the stack is empty. */ bool empty() { return q1.empty() ? true : false; } }; /** * Your MyStack object will be instantiated and called as such: * MyStack* obj = new MyStack(); * obj->push(x); * int param_2 = obj->pop(); * int param_3 = obj->top(); * bool param_4 = obj->empty(); */
单队列
class MyStack { private: queue<int> q; public: /** Initialize your data structure here. */ MyStack() { } /** Push element x onto stack. */ void push(int x) { // 反转队列,将新元素插到队头 int size = q.size(); q.push(x); while (size--){ int temp = q.front(); q.pop(); q.push(temp); } } /** Removes the element on top of the stack and returns that element. */ int pop() { int popEle = q.front(); q.pop(); return popEle; } /** Get the top element. */ int top() { return q.front(); } /** Returns whether the stack is empty. */ bool empty() { return q.empty(); } };
浙公网安备 33010602011771号