push,pop,top,size,empty这些操作对于栈来说常量时间的,但是要想实现min,max的常量时间操作需要增加两个栈,一个用于维护最小值,一个用于维护最大值。例如,对于min,每次入栈时将小于等于min栈顶的数值也压到min栈,出栈是如果值等于min的栈顶,将min的栈顶出栈。
以下是实现的代码,并不复杂。
#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;
};
int main()
{
xstack<int> s;
s.push(199);
s.push(201);
s.push(101);
cout << s.size() << s.top() << s.min() << s.max() << endl;
s.push(245);
cout << s.size() << s.top() << s.min() << s.max() << endl;
s.pop();
s.pop();
s.pop();
cout << (s.empty() ? "empty" : "not empty") << endl;
return 0;
}
本文介绍了如何使用双栈来实现栈的基本操作(push、pop、top、size、empty)的同时,还能在常量时间内获取最小值和最大值。通过在每次入栈时将小于等于当前最小值的数压入最小值栈,以及将大于等于当前最大值的数压入最大值栈,可以确保在出栈时仅需检查这两个栈的栈顶元素即可得到所需值。
2475

被折叠的 条评论
为什么被折叠?



