class Queue {
public:
// Push element x to the back of queue.
stack<int> ans;
void push(int x) {
ans.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
stack<int>res;
while(ans.size() > 1){
res.push(ans.top());
ans.pop();
}
if(ans.size() > 0) ans.pop();
while(res.size() > 0){
ans.push(res.top());
res.pop();
}
}
// Get the front element.
int peek(void) {
if(ans.size() == 0) return 0;
stack<int> res;
while(ans.size() > 0){
res.push(ans.top());
ans.pop();
}
int x = res.top();
while(res.size() > 0){
ans.push(res.top());
res.pop();
}
return x;
}
// Return whether the queue is empty.
bool empty(void) {
return ans.size() == 0;
}
};
leetcode 232. Implement Queue using Stacks
最新推荐文章于 2023-01-14 11:29:42 发布