DAY 10
class MyQueue {
public:
stack<int> p;
stack<int> q;
MyQueue() {
}
void push(int x) {
p.push(x);
}
int pop() {
if(q.empty())
{
while(!p.empty())
{
q.push(p.top());
p.pop();
}
}
int result = q.top();
q.pop();
return result;
}
int peek() {
if(q.empty())
{
while(!p.empty())
{
q.push(p.top());
p.pop();
}
}
int result = q.top();
return result;
}
bool empty() {
return p.empty() && q.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();
*/
class MyStack {
public:
queue<int> que1;
queue<int> que2;
MyStack() {
}
void push(int x) {
que1.push(x);
}
int pop() {
int n = que1.size();
n--;
//栈顶元素为队尾元素,这里把队头元素全部移除了,就只剩队尾元素了。返回队尾元素,再恢复出去队尾元素以外的元素。将que2清空。
if(que2.empty())
{
while(n--)
{
que2.push(que1.front());
que1.pop();
}
}
//移除完的最后一个元素即为栈顶元素,因为后进来的才是栈顶元素
int result = que1.front();
que1.pop();
que1 = que2;
while(!que2.empty())
{
que2.pop();
}
return result;
}
int top() {
return que1.back(); //这里直接返回队尾元素即可。
}
bool empty() {
return que1.empty() && que2.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();
*/