【发布时间】:2014-08-06 10:19:12
【问题描述】:
我想在 Java 中使用 HashMap 实现一个堆栈。 有什么方法可以实现吗?
【问题讨论】:
-
你可以使用哈希表来模拟一个数组,然后在数组上构建堆栈,但是你为什么要这样做呢?
标签: data-structures hashmap stack
我想在 Java 中使用 HashMap 实现一个堆栈。 有什么方法可以实现吗?
【问题讨论】:
标签: data-structures hashmap stack
试试这个代码:
public class FrequencyStack<T> {
private final Map<T, Integer> countMap = new HashMap<T, Integer>();
private final Map<Integer, Set<T>> stackMap = new HashMap<Integer, Set<T>>();
private int maxCount = 0;
public void push(T o) {
Integer c = countMap.get(o);
if (c == null) {
countMap.put(o, c = 1);
} else {
countMap.put(o, ++c);
}
Set<T> set = stackMap.get(c);
if (set == null)
stackMap.put(c, set = new LinkedHashSet<T>());
set.add(o);
if (c > maxCount)
maxCount = c;
}
public T pop() {
if (maxCount == 0)
return null;
Set<T> set = stackMap.get(maxCount);
T o = set.iterator().next();
set.remove(o);
if (maxCount == 1) {
countMap.remove(o);
}
if (set.size() == 0) {
stackMap.remove(maxCount);
--maxCount;
}
return o;
}
public T top() {
if (maxCount == 0)
return null;
return stackMap.get(maxCount).iterator().next();
}
}
【讨论】: