此帖仅作打卡用,过于简单,建议跳过
232.用栈实现队列
根据题意,用俩栈来回倒就行
code
class MyQueue {
public:
stack<int> q1;
stack<int> q2;
MyQueue() {}
void push(int x) {
while(!q2.empty()){
int pipe = q2.top();
q2.pop();
q1.push(pipe);
}
q1.push(x);
}
int pop() {
while(!q1.empty()){
int pipe = q1.top();
q1.pop();
q2.push(pipe);
}
int ans = q2.top();
q2.pop();
return ans;
}
int peek() {
while(!q1.empty()) {
int pipe = q1.top();
q1.pop();
q2.push(pipe);
}
return q2.top();
}
bool empty() {
return q1.empty() && q2.empty();
}
};
225.用队列实现栈
一个双端队列完事
code
class MyStack {
public:
deque<int> d1;
MyStack() {}
void push(int x) {
d1.push_front(x);
}
int pop() {
int p = d1.front();
d1.pop_front();
return p;
}
int top() {
return d1.front();
}
bool empty() {
return d1.empty();
}
};