1、描述
2、关键字
栈、队列
3、思路
1、两个栈实现一个队列,模拟过程
2、还有一个分摊思想:就是当取队列队首元素的时候,可以标记第一个栈的栈底元素,当第二个栈为空时后,可以时间复杂度为O(1)提前把对列的首元素返回出去,(提前消费思想),不过后面还得把该干的活:(转移元素到第二个栈,)都干了。说是分摊思想。
4、notes
1、把两个栈之间的转移动作抽取出来用一个函数表示,显得更好,pop()peek()都可能用到这个转移动作会重复代码。
5、复杂度
时间:O(N)
空间:O(N)
6、code
class MyQueue {
private:
stack<int>st1,st2;
public:
/** Initialize your data structure here. */
MyQueue() { }
void push(int x) {
st1.push(x); //push()只需要直接进第一个栈
}
int pop() {
transfer(); // 如果需要就转移,
int tem;
tem=st2.top();
st2.pop();
return tem;
}
int peek() {
transfer();
int res;
res=st2.top();
return res;
}
bool empty() {
return st2.empty()&&st1.empty();
}
void transfer(){ // 把这个转移的动作抽取出来一个函数
if(st2.empty()) // 如果第二个栈为空了,才转移
{
while(!st1.empty()) // 把当前第一个栈内的所有元素都转移过去
{
st2.push(st1.top());
st1.pop();
}
}
}
};
/**
* 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();
*/
6.2没抽取动作的代码
pop函数st2的时候别落了st2.pop()!!!
class MyQueue {
private:
stack<int>st1,st2;
public:
/** Initialize your data structure here. */
MyQueue() { }
/** Push element x to the back of queue. */
void push(int x) {
st1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int tem;
if(!st2.empty())
{
tem=st2.top();
st2.pop();
}else
{
while(!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
tem=st2.top();
st2.pop();
}
return tem;
}
/** Get the front element. */
int peek() {
int res;
if(!st2.empty())
{
res=st2.top();
}
else{
while(!st1.empty())
{
st2.push(st1.top());
st1.pop();
}
res=st2.top();//
}
return res;
}
/** Returns whether the queue is empty. */
bool empty() {
return st2.empty()&&st1.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();
*/