要求:
void push(int x)
将元素 x 推到队列的末尾int pop()
从队列的开头移除并返回元素int peek()
返回队列开头的元素boolean empty()
如果队列为空,返回true
;否则,返回false
思路:设置两个栈,一个in栈一个out栈,如图
push直接push。
pop则需要在out栈为空时进行操作,把in栈的栈顶元素push到out里,再把out栈的元素pop出来,中间用result来存,最后返回result。
peek:
- 首先,通过调用
this->pop()
来弹出栈顶元素,并将结果存储在变量res
中。pop()
函数通常会从栈中移除并返回栈顶元素。 - 然后,
stOut.push(res)
将刚弹出的元素res
压回到stOut
栈中。这一步是为了恢复栈的原始状态,因为pop()
函数会移除栈顶元素。 - 最后,函数返回
res
,即栈顶元素的值,但不从栈中移除它。
empty就是in和out都为空则返回。
题解c++:
class MyQueue {
public:
stack<int> in;
stack<int> out;
MyQueue() {
}
void push(int x) {
in.push(x);
}
int pop() {
if(out.empty())
{
while(!in.empty())
{
out.push(in.top());
in.pop();
}
}
int result=out.top();
out.pop();
return result;
}
int peek() {
int res=this->pop();
out.push(res);
return res;
}
bool empty() {
return in.empty()&&out.empty();
}
};
/**
* 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();
*/