O
问题
解决方案
代码
/*
思路: 两个栈怎么模拟呢? 一个只能先进后出, 另外一个能下进,上出。 我们在code中逐步思考。
-
-
- -
- -
-
*/
class MyQueue {
public:
stack<int> in ,out;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(out.empty()){
while(!in.empty()){
int x = in.top();
in.pop();
out.push(x);
}
}
int x = out.top();
out.pop();
return x;
}
/** Get the front element. */
int peek() {
if(out.empty()){
while(!in.empty()){
int x = in.top();
in.pop();
out.push(x);
}
}
int x = out.top();
return x;
}
/** Returns whether the queue is empty. */
bool empty() {
if(in.empty()&&out.empty()) return true;
else return false;
}
};
/**
* 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();
*/
总结与反思
- 注意如何使用pop ,top等。 api还是不熟悉。