user3788005
user3788005

Reputation: 27

How to implement a stack using HashMap in Java?

I would like to Implement a stack using HashMap in Java. Is there any way to achieve that?

Upvotes: 2

Views: 5379

Answers (1)

Suchit kumar
Suchit kumar

Reputation: 11859

Try this code:

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();
    }   
}

Upvotes: 1

Related Questions