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.");
}
};