法一:使用两个栈模拟队列。
class Queue {
private:
stack<int> q_input;
stack<int> q_output;
public:
// Push element x to the back of queue.
void push(int x) {
q_input.push(x);
}
// Removes the element from in front of queue.
void pop(void) {
while(!q_input.empty())
{
int top_tmp = q_input.top();
q_input.pop();
q_output.push(top_tmp);
}
if(!q_output.empty())
q_output.pop();
while(!q_output.empty())
{
int top_tmp = q_output.top();
q_output.pop();
q_input.push(top_tmp);
}
}
// Get the front element.
int peek(void) {
while(!q_input.empty())
{
int top_tmp = q_input.top();
q_input.pop();
q_output.push(top_tmp);
}
int result = 0;
if(!q_output.empty())
result = q_output.top();
while(!q_output.empty())
{
int top_tmp = q_output.top();
q_output.pop();
q_input.push(top_tmp);
}
return result;
}
// Return whether the queue is empty.
bool empty(void) {
return q_input.empty();
}
};
优美的写法:
class Queue {
stack<int> input, output;
public:
void push(int x) {
input.push(x);
}
void pop(void) {
peek();
output.pop();
}
int peek(void) {
if (output.empty())
while (input.size())
output.push(input.top()), input.pop();
return output.top();
}
bool empty(void) {
return input.empty() && output.empty();
}
};
法二:高效使用stack,使用递归来做
class Queue {
public:
stack<int> s;
// Push element x to the back of queue.
void push(int x) {
pushHelper(x);
}
void pushHelper(int x){
if(s.size()==0){
s.push(x);
return;
}
int data;
data = s.top();
s.pop();
pushHelper(x);
s.push(data);
return;
}
// Removes the element from in front of queue.
void pop(void) {
s.pop();
}
// Get the front element.
int peek(void) {
return s.top();
}
// Return whether the queue is empty.
bool empty(void) {
return (s.size()==0);
}
};