实现原理是使用两个stack,每当peek或者pop时将stack in中的元素全部转移到out。借此实现先入先出。
最初始的代码实现为:
class MyQueue {
public:
/** 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())
{
out.push(in.top());
in.pop();
}
}
int elem = out.top();
out.pop();
return elem;
}
/** Get the front element. */
int peek() {
if(out.empty())
{
while(!in.empty())
{
out.push(in.top());
in.pop();
}
}
int elem = out.top();
return elem;
}
/** Returns whether the queue is empty. */
bool empty() {
cout <<in.empty() << " "<<out.empty();
return in.empty() && out.empty();
}
private:
stack<int> in;
stack<int> out;
};
/**
* 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();
*/
优化后的代码实现:
class MyQueue {
public:
/** 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() {
int val = peek();
out.pop();
return val;
}
/** Get the front element. */
int peek() {
if(out.empty())
{
while(in.size())
out.push(in.top()),in.pop();
}
return out.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return in.empty() && out.empty();
}
private:
stack<int> in, out;
};
/**
* 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();
*/
另一种实现方法是利用函数调用栈,每次插入元素时将待插入元素插到栈底。
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
push_helper(x);
}
void push_helper(int x){
if(s.size() == 0)
{
s.push(x);
return;
}
int val = s.top();
s.pop();
push_helper(x);
s.push(val);
return;
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int val = s.top();
s.pop();
return val;
}
/** Get the front element. */
int peek() {
return s.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return s.empty();
}
private:
stack<int> s;
};
/**
* 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();
*/