232. Implement Queue using Stacks
题目还是不难,就是stack和queue的各种函数和操作需要记一下。思路就是用两个stack,一个座位出,另一个作为入;
class MyQueue {
public:
stack<int> In;
stack<int> Out;
MyQueue() {
//stack<int> In;
//stack<int> Out;这两行不能放在这里面
}
void push(int x) {
In.push(x);
}
int pop() {
if(Out.empty() == 1) { //这个empty函数不会用
while(In.empty() != 1) {
Out.push(In.top());
In.pop();
}
}
int result = Out.top();
Out.pop();
return result;
}
/** Get the front element. */
int peek() {
// 方法是把最上面的那个数弹出来,然后再加进去,在这个过程中赋值
int result = this->pop();
Out.push(result);
return result;
}
bool empty() {
return In.empty() && Out.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
232. Implement Queue using Stacks
class MyQueue {
public:
stack<int> In;
stack<int> Out;
MyQueue() {
//stack<int> In;
//stack<int> Out;这两行不能放在这里面
}
void push(int x) {
In.push(x);
}
int pop() {
if(Out.empty() == 1) { //这个empty函数不会用
while(In.empty() != 1) {
Out.push(In.top());
In.pop();
}
}
int result = Out.top();
Out.pop();
return result;
}
/** Get the front element. */
int peek() {
// 方法是把最上面的那个数弹出来,然后再加进去,在这个过程中赋值
int result = this->pop();
Out.push(result);
return result;
}
bool empty() {
return In.empty() && Out.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/