232. 用栈实现队列
在push数据的时候,只要数据放进输入栈就好,
pop的时候,操作就复杂一些,输出栈如果为空,就把进栈数据全部导入进来(注意是全部导入),再从出栈弹出数据,如果输出栈不为空,则直接从出栈弹出数据就可以了。
peek函数比pop函数少了一个删除栈顶元素的操作,可以进行代码复用,在peek写逻辑,可以避免先把元素拿出栈再出栈
class MyQueue {
public:
stack<int>s1;
stack<int>s2;
MyQueue() {
}
void push(int x) {
s1.push(x);
}
int pop() {
int x = peek();
s2.pop();
return x;
}
int peek() {
int x;
if(s2.empty()){
while(!s1.empty()){
s2.push(s1.top());
s1.pop();
}
}
x = s2.top();
return x;
}
bool empty() {
if(s1.empty() && s2.empty()) return true;
return false;
}
};
1.两个队列
将push的元素先放到一个空队列里,然后将另一个非空的队列pop()到这个队列 那么顺序就是对的,一个非空队列和一个空队列轮流倒腾
class MyStack {
public:
queue<int>q1;
queue<int>q2;
MyStack() {
}
void push(int x) {
if(empty() || q1.empty()){
q1.push(x);
while(!q2.empty()){
int temp = q2.front();
q2.pop();
q1.push(temp);
}
}
else {
q2.push(x);
while(!q1.empty()){
int temp = q1.front();
q1.pop();
q2.push(temp);
}
}
}
int pop() {
int topp = top();
if(q1.empty()) q2.pop();
else q1.pop();
return topp;
}
int top() {
if(q1.empty()) return q2.front();
else return q1.front();
}
bool empty() {
if(q1.empty() && q2.empty()){
return true;
}
return false;
}
};
一个队列自己倒腾
一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外) 重新添加到队列尾部,此时再去弹出元素就是栈的顺序了。
class MyStack {
public:
queue<int>q;
MyStack() {
}
void push(int x) {
q.push(x);
}
int pop() {
int size = q.size()-1;
int x;
while(size--){
q.push(q.front());
q.pop();
}
x = q.front();
q.pop();
return x;
}
int top() {
int x = pop();
q.push(x);
return x;
}
bool empty() {
return q.empty();
}
};