首页 > 代码库 > [Twitter] Max Stack
[Twitter] Max Stack
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(); } }
[Twitter] Max Stack
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。