232 用栈实现队列
class MyQueue {
public:
stack<int> st_in;
stack<int> st_out;
MyQueue() {
}
void push(int x) {
st_in.push(x);
}
int pop() {
if(st_out.empty()) {
while(!st_in.empty()) {
st_out.push(st_in.top());
st_in.pop();
}
}
int a = st_out.top();
st_out.pop();
return a;
}
int peek() {
int element = this->pop();
st_out.push(element);
return element;
}
bool empty() {
return st_in.empty() && st_out.empty();
}
};
225 用队列实现栈
class MyStack {
public:
queue<int> x;
queue<int> y;
MyStack() {
}
void push(int x) {
this->x.push(x);
}
int pop() {
int size = x.size();
while(x.size() > 1) {
y.push(x.front());
x.pop();
}
int element = x.front();
x.pop();
while(y.size()>0) {
x.push(y.front());
y.pop();
}
return element;
}
int top() {
int size = x.size();
while(x.size() > 1) {
y.push(x.front());
x.pop();
}
int element = x.front();
x.pop();
y.push(element);
while(y.size()>0) {
x.push(y.front());
y.pop();
}
return element;
}
bool empty() {
return x.empty();
}
};