1.使用辅助栈实现
class MyQueue {
public:
stack<int> a,b;
MyQueue() {
}
void push(int x) {
a.push(x);
}
int pop() {
while(a.size()>1) b.push(a.top()),a.pop();
int t=a.top();
a.pop();
while(b.size()) a.push(b.top()),b.pop();
return t;
}
int peek() {
while(a.size()>1) b.push(a.top()),a.pop();
int t=a.top();
while(b.size()) a.push(b.top()),b.pop();
return t;
}
bool empty() {
return a.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();
*/
2.和上一题不同的是这里不删front然后直接插会导致top在队列头,所以必须删掉再插到尾
public:
queue<int> a,b;
MyStack() {
}
void push(int x) {
a.push(x);
}
int pop() {
while(a.size()>1) b.push(a.front()),a.pop();
auto t=a.front();
a.pop();
while(b.size()) a.push(b.front()),b.pop();
return t;
}
int top() {
while(a.size()>1) b.push(a.front()),a.pop();
auto t=a.front();
a.pop();
while(b.size()) a.push(b.front()),b.pop();
a.push(t);
return t;
}
bool empty() {
return a.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();
*/