@requires_authorization
@author johnsondu
@create_time 2015.8.6 19:28
@url <a target=_blank href="https://leetcode.com/problems/implement-queue-using-stacks/">Implement Queue using Stacks</a>
/**
* @description: emumerate.
* @time_complexity: O(n)
* @space_complexity: O(n)
*/
class Queue {
public:
stack<int> in;
stack<int> out;
// Push element x to the back of queue.
void push(int x) {
in.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
if(!out.empty()) out.pop();
else{
while(!in.empty()){
int val = in.top();
out.push(val);
in.pop();
}
out.pop();
}
}
// Get the front element.
int peek(void) {
if(!out.empty()) return out.top();
else{
while(!in.empty()) {
int val = in.top();
in.pop();
out.push(val);
}
return out.top();
}
}
// Return whether the queue is empty.
bool empty(void) {
return (in.empty() && out.empty());
}
};
【leetcode】232. Implement Queue using Stacks
最新推荐文章于 2021-05-21 15:00:42 发布