要想实现带有min,max常量时间操作的队列,不能直接通过增加额外的空间来实现,但是可以通过使用带有min,max常量时间操作的两个栈来实现!
栈1用于接受加入队列的数据,push操作时总是会把数据压入栈1,pop时总是弹出栈2,如果栈2为空是就将栈1的数据依次弹出压入栈2!这样便使用两个栈实现了一个队列,由于栈有常量时间的min,max操作,队列也拥有了常量时间的min,max操作。
#include <iostream>
#include <stack>
using namespace std;
template<typename type>
class xstack
{
public:
void push(const type v) {
if (stk.empty()) {
min_stk.push(v);
max_stk.push(v);
} else {
if (v <= min_stk.top())
min_stk.push(v);
if (v >= max_stk.top())
max_stk.push(v);
}
stk.push(v);
}
void pop() {
type v = stk.top();
if (v == min_stk.top())
min_stk.pop();
if (v == max_stk.top())
max_stk.pop();
stk.pop();
}
type top() {
return stk.top();
}
size_t size() {
return stk.size();
}
bool empty() {
return stk.empty();
}
type min() {
return min_stk.top();
}
type max() {
return max_stk.top();
}
private:
stack<type> stk;
stack<type> min_stk;
stack<type> max_stk;
};
template<typename type>
class xqueue
{
public:
void push(const type v) {
stk1.push(v);
}
void pop() {
type v = front();
stk2.pop();
}
type front() {
if (stk2.empty()) {
while (!stk1.empty()) {
stk2.push(stk1.top());
stk1.pop();
}
}
return stk2.top();
}
size_t size() {
return stk1.size() + stk2.size();
}
bool empty() {
return stk1.empty() && stk2.empty();
}
type min() {
if (stk1.empty() && !stk2.empty())
return stk2.min();
if (!stk1.empty() && stk2.empty())
return stk1.min();
return std::min(stk1.min(), stk2.min());
}
type max() {
if (stk1.empty() && !stk2.empty())
return stk2.max();
if (!stk1.empty() && stk2.empty())
return stk1.max();
return std::max(stk1.max(), stk2.max());
}
private:
xstack<type> stk1;
xstack<type> stk2;
};
int main()
{
xqueue<int> x;
x.push(9);
x.push(5);
x.push(8);
cout << x.min() << " " << x.max()<< endl;
x.push(6);
x.push(1);
cout << x.min() << " " << x.max()<< endl;
x.push(4);
x.push(3);
x.push(2);
cout << x.min() << " " << x.max()<< endl;
x.push(7);
x.push(0);
x.pop();
x.pop();
cout << x.min() << " " << x.max()<< endl;
return 0;
}