Question:
Design a max stack using one stack. ?
One stack? I think it is two stacks.
class MaxMinStack<T> { private Stack<T> data; private Stack<T> max; private Stack<T> min; private Comparator<T> comparator; public MaxMinStack<T>(Comparator comparator) { Validate.notNull(comparator); data = new Stack<>(); min = new Stack<>(); max = new Stack<>(); this.comparator = comparator; } public void push(T t) { Validate.notNull(t); data.push(t); if (max.empty() || comparator.compare(t, max.peek()) >= 0) { max.push(t); } if (min.empty() || comparator.compare(t, min.peek()) <= 0) { min.push(t); } } public T pop() { if (data.empty()) return null; T t = data.pop(); if (comparator.compare(t, max.peek()) == 0) max.pop(); if (comparator.compare(t, max.peek()) == 0) min.pop(); return t; } public T max() { return max.empty() ? null : max.peek(); } public T min() { return min.empty() ? null : min.peek(); } }
时间: 2024-10-08 17:20:37