class ReverseOrderBuilder<N> {

    private final DirectedGraph<N> graph;
    private final int graphSize;
    private final int[] indexStack;
    private final N[] stmtStack;
    private final Set<N> visited;
    private final N[] order;
    private int orderLength;

    /**
     * @param g
     *          a DirectedGraph instance we want to order the nodes for.
     */
    public ReverseOrderBuilder(DirectedGraph<N> g) {
      this.graph = g;
      final int n = g.size();
      this.graphSize = n;
      this.visited = Collections.newSetFromMap(new IdentityHashMap<N, Boolean>(n * 2 + 1));
      this.indexStack = new int[n];
      @SuppressWarnings("unchecked")
      N[] tempStmtStack = (N[]) new Object[n];
      this.stmtStack = tempStmtStack;
      @SuppressWarnings("unchecked")
      N[] tempOrder = (N[]) new Object[n];
      this.order = tempOrder;
      this.orderLength = 0;
    }

    /**
     * Orders in pseudo-topological order.
     * 
     * @param reverse
     *          specify if we want reverse pseudo-topological ordering, or not.
     * @return an ordered list of the graph's nodes.
     */
    public List<N> computeOrder(boolean reverse) {<FILL_FUNCTION_BODY>}

    // Unfortunately, the nice recursive solution fails
    // because of stack overflows
    // Fill in the 'order' list with a pseudo topological order
    // list of statements starting at s. Simulates recursion with a stack.
    private void visitNode(N startStmt) {
      int last = 0;

      stmtStack[last] = startStmt;
      indexStack[last++] = -1;
      while (last > 0) {
        int toVisitIndex = ++indexStack[last - 1];
        N toVisitNode = stmtStack[last - 1];

        List<N> succs = graph.getSuccsOf(toVisitNode);
        if (toVisitIndex >= succs.size()) {
          // Visit this node now that we ran out of children
          order[orderLength++] = toVisitNode;

          last--;
        } else {
          N childNode = succs.get(toVisitIndex);

          if (visited.add(childNode)) {
            stmtStack[last] = childNode;
            indexStack[last++] = -1;
          }
        }
      }
    }

    /**
     * Reverses the order of the elements in the specified array.
     * 
     * @param array
     */
    private static <T> void reverseArray(T[] array) {
      final int max = array.length >> 1;
      for (int i = 0, j = array.length - 1; i < max; i++, j--) {
        T temp = array[i];
        array[i] = array[j];
        array[j] = temp;
      }
    }
  }

      // Visit each node
      for (N s : graph) {
        if (visited.add(s)) {
          visitNode(s);
        }
        if (orderLength == graphSize) {
          break;
        }
      }

      if (reverse) {
        reverseArray(order);
      }
      return Arrays.asList(order);
    
<no_super_class>