方法:栈
class MyQueue {
public:
stack<int> Istk, Ostk;
MyQueue() {
}
void push(int x) {
Istk.push(x);
}
int pop() {
while (Ostk.empty()) {
while (!Istk.empty()) {
Ostk.push(Istk.top());
Istk.pop();
}
}
int res = Ostk.top();
Ostk.pop();
return res;
}
int peek() {
int res = this->pop();
Ostk.push(res);
return res;
}
bool empty() {
return Ostk.empty() && Istk.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();
*/
$时间复杂度O(1),空间复杂度O(n)
方法:队列
class MyStack {
public:
queue<int> que;
MyStack() {
}
void push(int x) {
que.push(x);
}
int pop() {
int size = que.size();
size--;
while (size--) {
que.push(que.front());
que.pop();
}
int res = que.front();
que.pop();
return res;
}
int top() {
return que.back();
}
bool empty() {
return que.empty();
}
};
/**
* 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();
*/
$时间复杂度O(n),空间复杂度O(n)