class DirectedGraph {

    public List<V> topologicalSort() {
        Map<V, Integer> degree = inDegree();

        // determine all vertices with zero in-degree
        Stack<V> zeroVertices = new Stack<>(); // stack as good as any here
        for (V v : degree.keySet()) {
            if (degree.get(v) == 0) {
                zeroVertices.push(v);
            }
        }

        // determine the topological order
        List<V> result = new ArrayList<>();
        while (!zeroVertices.isEmpty()) {
            V vertex = zeroVertices.pop(); // choose a vertex with zero in-degree
            result.add(vertex); // vertex 'v' is next in topological order
            // "remove" vertex 'v' by updating its neighbors
            for (V neighbor : neighbors.get(vertex)) {
                degree.put(neighbor, degree.get(neighbor) - 1);
                // remember any vertices that now have zero in-degree
                if (degree.get(neighbor) == 0) {
                    zeroVertices.push(neighbor);
                }
            }
        }

        // check that we have used the entire graph (if not, there was a cycle)
        if (result.size() != neighbors.size()) {
            return null;
        }

        return result;
    }

}