232. 用栈实现队列
输出栈如果为空,就把进栈数据全部导入进来,再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据。
class MyQueue {
public:
stack<int> st1;
stack<int> st2;
MyQueue() {
}
void push(int x) {
st1.push(x);
}
int pop() {
if(!st2.empty()) {
int ans = st2.top();
st2.pop();
return ans;
}
while(!st1.empty()){
st2.push(st1.top());
st1.pop();
}
int ans1 = st2.top();
st2.pop();
return ans1;
}
int peek() {
int ans = this->pop();
st2.push(ans);
return ans;
}
bool empty() {
return st1.empty() && st2.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();
*/
225. 用队列实现栈
class MyStack {
public:
//queue2始终为空
queue<int> queue1;
queue<int> queue2;
MyStack() {
}
void push(int x) {
queue2.push(x);
while(!queue1.empty()){
queue2.push(queue1.front());
queue1.pop();
}
//不用swap
queue1 = queue2; // 再将que2赋值给que1
while (!queue2.empty()) { // 清空que2
queue2.pop();
}
}
int pop() {
int ans = queue1.front();
queue1.pop();
return ans;
}
int top() {
return queue1.front();
}
bool empty() {
return queue1.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();
*/
class MyStack {
public:
queue<int> q1;
queue<int> q2;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size = q1.size()-1;
while(size--){
q2.push(q1.front());
q1.pop();
}
int ans = q1.front();
q1.pop();
while(!q2.empty()){
q1.push(q2.front());
q2.pop();
}
return ans;
}
int top() {
int ans = this->pop();
q1.push(ans);
return ans;
}
bool empty() {
return q1.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();
*/