class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> s1, s2;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int size = s1.size();
for(int i = 0; i < size; i++)
{
int tmp = s1.top();
s1.pop();
s2.push(tmp);
}
int cur = s2.top();
s2.pop();
while(!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return cur;
}
/** Get the front element. */
int peek() {
int size = s1.size();
for(int i = 0; i < size; i++)
{
int tmp = s1.top();
s1.pop();
s2.push(tmp);
}
int cur = s2.top();
while(!s2.empty())
{
s1.push(s2.top());
s2.pop();
}
return cur;
}
/** Returns whether the queue is empty. */
bool empty() {
if(!s1.empty())
return false;
else
return true;
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
用两个栈实现队列
最新推荐文章于 2024-02-21 17:10:17 发布