CareerCup 3.2

来源:互联网 发布:手机数据彻底清除方法 编辑:程序博客网 时间:2024/04/28 01:06

3.2 How would you design a stack which, in addition to push and pop, also has a functionminwhich 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.");    }};

原创粉丝点击