3.2 How would you design a stack which, in addition to push and pop, also has a functionmin which returns the minimum element?Push, pop and min should all operate in O(1) time.
Solution 1:
template <typename T>
class StackWithMin {
private:
stack<pair<T, T> > s;
public:
bool isEmpty() const {
return s.empty();
}
const T& min() const {
if (!s.empty()) {
return s.top().second;
}
throw length_error("Stack is empty.");
}
void push(const T &value) {
T m = value;
if (!s.empty()) {
m = min(m, s.top().second);
}
s.push(value, m);
}
T pop() {
if (!s.empty()) {
T value = s.top().first;
s.pop();
return value;
}
throw length_error("Stack is empty.");
}
};Solution 2:
template <typename T>
class StackWithMin {
private:
stack<T> s;
stack<T> m;
public:
bool isEmpty() const {
return s.empty();
}
const T& min() const {
if (!s.empty()) {
return m.top();
}
throw length_error("Stack is empty.");
}
void push(const T &value) {
if (s.empty()) {
s.push(value);
m.push(value);
} else if (value <= m.top()) {
s.push(value);
m.push(value);
} else {
s.push(value);
}
}
T pop() {
if (!s.empty()) {
T value = s.top();
s.pop();
if (value == m.top()) {
m.pop();
}
return value;
}
throw length_error("Stack is empty.");
}
};
本文介绍如何设计一种特殊的数据结构——栈,在保持基本的push和pop操作为O(1)时间复杂度的同时,新增一个min函数用以返回栈中的最小元素,同样保证O(1)的时间复杂度。提供了两种解决方案,一种使用带有元组的单一栈,另一种采用两个独立栈的方法。
520

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



