232.用栈实现队列(题目链接:力扣)
思路:用栈实现对列,一开始忘记了c++中的栈操作,重新复习了一下,c++中栈、队列的push()、pop()方法都是没有返回值的,栈的顶部元素用top()方法获得,队列的头部元素用front()方法获得。单个栈不用额外空间是没法实现队列的,但是单个队列只需要一个临时变量就可以实现栈,这是两者不同的地方。
class MyQueue {
public:
stack<int> stIn;
stack<int> stOut;
MyQueue() {
}
void push(int x) {
stIn.push(x);
}
int pop() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
int ans = stOut.top();
stOut.pop();
return ans;
}
int peek() {
if(stOut.empty()){
while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();
}
}
return stOut.top();
}
bool empty() {
return stIn.empty() && stOut.empty();
}
};
225. 用队列实现栈(题目链接:力扣)
思路:和上题差不多,这块儿直接上代码。
class MyStack {
public:
queue<int> q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size();
int ans;
while(--size){
ans = q.front();
q.pop();
q.push(ans);
}
ans = q.front();
q.pop();
return ans;
}
int top() {
int size = q.size();
int ans;
while(size--){
ans = q.front();
q.pop();
q.push(ans);
}
return ans;
}
bool empty() {
return q.empty();
}
};