232.用栈实现队列
题目链接: 232.用栈实现队列
注意事项:
- 在pop时最好添加判断栈是否为空的条件
class MyQueue {
public:
stack<int> sIn;
stack<int> sOut;
MyQueue() {
}
void push(int x) {
while(!sOut.empty()){
sIn.push(sOut.top());
sOut.pop();
}
sIn.push(x);
while(!sIn.empty()){
sOut.push(sIn.top());
sIn.pop();
}
}
int pop() {
int temp = sOut.top();
sOut.pop();
return temp;
}
int peek() {
return sOut.top();
}
bool empty() {
return sOut.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. 用队列实现栈
题目链接: 225. 用队列实现栈
class MyStack {
public:
queue<int> q1;
int size = 0;
MyStack() {
}
void push(int x) {
size++;
q1.push(x);
}
int pop() {
int count = size - 1;
while(count--){
int temp = q1.front();
q1.push(temp);
q1.pop();
}
int temp2 = q1.front();
q1.pop();
size--;
return temp2;
}
int top() {
int count = size - 1;
while(count--){
int temp = q1.front();
q1.push(temp);
q1.pop();
}
int temp2 = q1.front();
q1.push(q1.front());
q1.pop();
return temp2;
}
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();
*/