//问题:设计一个队列能够在O(1)时间内取得队列的最大值
#include <stdio.h>
#include <queue>
#include <stack>
//O(1)的速度取出栈中的最大值
template<typename T>
class MaxStack
{
public:
//入栈
void Push(const T& value)
{
data_.push(value);
if (max_element_.empty())
{
max_element_.push(value);
}
else if (value >= max_element_.top())
{
max_element_.push(value);
}
}
//返回栈顶元素
T Top()
{
return data_.top();
}
//出栈
void Pop()
{
if (data_.top() == max_element_.top())
{
max_element_.pop();
}
data_.pop();
}
//判断是否为空
bool Empty()
{
return data_.empty();
}
//取出最大值
T Max()
{
if (!max_element_.empty())
{
return max_element_.top();
}
}
private:
std::stack<T> data_;
std::stack<T> max_element_;
};
//O(1)的速度取出队列中的最大值
template<typename T>
class MaxQueue
{
public:
//入队操作!!!!
void Push(const T& value)
{
push_stack_.Push(value);
}
//取队首元素
T Front()
{
if (pop_stack_.empty())
{
while (!push_stack_.Empty())
{
pop_stack_.Push(push_stack_.Top());
push_stack_.Pop();
}
}
return pop_stack_.Top();
}
//出队操作!!!!
void Pop()
{
if (pop_stack_.Empty())
{
while (!push_stack_.Empty())
{
pop_stack_.Push(push_stack_.Top());
push_stack_.Pop();
}
}
pop_stack_.Pop();
}
//判空操作!!!!!
bool IsEmpty()
{
return push_stack_.Empty() && pop_stack_.Empty();
}
//取出最大值
T Max()
{
if (!push_stack_.Empty() && !pop_stack_.Empty())
{
return push_stack_.Max() > pop_stack_.Max() ? push_stack_.Max() : pop_stack_.Max();
}
else if (push_stack_.Empty() && !pop_stack_.Empty())
{
return pop_stack_.Max();
}
else if (!push_stack_.Empty() && pop_stack_.Empty())
{
return push_stack_.Max();
}
else
{
throw RUNTIME_ERROR;
}
}
private:
MaxStack<T> push_stack_;
MaxStack<T> pop_stack_;
};
//测试用例
int main(int argc, char** argv)
{
MaxQueue<int> max_queue;
max_queue.Push(1);
max_queue.Push(2);
max_queue.Push(6);
max_queue.Push(4);
max_queue.Push(5);
max_queue.Push(2);
printf("max %d\n", max_queue.Max());
max_queue.Pop();
printf("max %d\n", max_queue.Max());
max_queue.Pop();
printf("max %d\n", max_queue.Max());
max_queue.Pop();
printf("max %d\n", max_queue.Max());
max_queue.Pop();
printf("max %d\n", max_queue.Max());
max_queue.Pop();
printf("max %d\n", max_queue.Max());
}