leetcode 232. Implement Queue using Stacks
class MyQueue { public: /** Initialize your data structure here. */ stack<int> r, b; MyQueue() { } /** Push element x to the back of queue. */ void push(int x) { r.push(x); } /** Removes the element from in front of queue and returns that element. */ int pop() { if (b.empty()) { int size = r.size(); for (int i = 0; i < size; i++) { int t = r.top(); b.push(t); r.pop(); } } int ret = b.top(); b.pop(); return ret; } /** Get the front element. */ int peek() { if (b.empty()) { int size = r.size(); for (int i = 0; i < size; i++) { int t = r.top(); b.push(t); r.pop(); } } return b.top(); } /** Returns whether the queue is empty. */ bool empty() { return r.empty() && b.empty(); } };
【本文章出自博客园willaty,转载请注明作者出处,误差欢迎指出~】