用栈实现队列:想到了用两个栈就容易了
class MyQueue {
public:
stack<int> s1;
stack<int> s2;
MyQueue() {}
void push(int x) { s1.push(x); }
int pop() {
if (s2.empty()) {
while (!s1.empty()) {
int yuansu = s1.top();
s2.push(yuansu);
s1.pop();
}
}
int yuansu2 = s2.top();
s2.pop();
return yuansu2;
}
int peek() {
int yuansu = pop();
s2.push(yuansu);
return yuansu;
}
bool empty() { return s1.empty() && s2.empty(); }
};
用队列实现栈:
class MyStack {
public:
queue<int> q1;
MyStack() {
}
void push(int x) {
q1.push(x);
}
int pop() {
int size=q1.size();
size--;
while(size--){
int qq=q1.front();
q1.pop();
q1.push(qq);
}
int qq=q1.front();
q1.pop();
return qq;
}
int top() {
return q1.back();
}
bool empty() {
return q1.empty();
}
};