day10打卡
时间复杂度:push、empty为O(1),pop、peek为O(N),空间复杂度:O(N)
push:正常使用栈的push
empty:判断两个栈都为空才是空
pop:把第一个栈的元素,放入第二个元素、再pop就符合正常队列的顺序了
peek:复用pop即可
class MyQueue {
public:
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty())
{
while(!stIn.empty())
{
int x = stIn.top();
stIn.pop();
stOut.push(x);
}
}
int x = stOut.top();
stOut.pop();
return x;
}
int peek() {
int x = this->pop();
stOut.push(x);
return x;
}
bool empty() {
return stIn.empty() && stOut.empty();
}
private:
stack<int> stIn;
stack<int> stOut;
};
/**
* 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();
*/
时间复杂度:pop为O(N)、其余O(1),空间复杂度:O(N)
push:正常使用队列的pop即可
empty:两个队列时,第二个队列仅仅充当为第一个队列保存数据的作用,所以判断第一个即可
pop:求出队列大小,为了保留栈顶元素做减1操作,其他元素pop出队列即可:两个队列时,边pop出q1,边push进q2;一个队列时,在同一个队列上做弹出弹入即可。
top:两个队列时,让q2临时保存q1,再仿照pop写即可;一个队列时复用pop即可
两个队列
class MyStack {
public:
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size = q1.size();
size--;
while(size--)
{
int x = q1.front();
q1.pop();
q2.push(x);
}
int x = q1.front();
q1.pop();
q1 = q2;
while(!q2.empty()) q2.pop();
return x;
}
int top() {
q2 = q1;
int size = q2.size();
size--;
while(size--) q2.pop();
int x = q2.front();
q2.pop();
return x;
}
bool empty() {
return q1.empty();
}
private:
queue<int> q1;
queue<int> q2;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/
一个队列
class MyStack {
public:
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
size--;
while(size--)
{
int x = q.front();
q.pop();
q.push(x);
}
int x = q.front();
q.pop();
return x;
}
int top() {
int x = this->pop();
q.push(x);
return x;
}
bool empty() {
return q.empty();
}
private:
queue<int> q;
};
/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/