title: StackOverFlowError when trying to use topological sorting on nodes that depend on each other
body: <p>I was developing a way to sort a list as if the elements that have dependants on others, are iterated first. I've come up with the following code:</p>
  <pre class="lang-java prettyprint-override"><code>record Node(String name, Set&lt;Node&gt; dependants)
  {
  }
  
  public class Main
  {
      public static void main(String[] args)
      {
          var nodeA = new Node(&quot;Node A&quot;, Collections.emptySet());       // No one depends on A
          var nodeB = new Node(&quot;Node B&quot;, Collections.singleton(nodeA)); // A depends on B
          var nodeC = new Node(&quot;Node C&quot;, Collections.singleton(nodeB)); // B depends on C
  
          List&lt;Node&gt; nodes = new ArrayList&lt;&gt;(Arrays.asList(nodeA, nodeB, nodeC));
  
          Collections.shuffle(nodes);
          sortInTopologicalOrder(nodes);
  
          // If A depends on B, and B depends on C, the print order is always C B A, since C depends on no one.
          nodes.forEach(node -&gt; System.out.println(node.name()));
      }
  
      static void sortInTopologicalOrder(List&lt;Node&gt; toSort)
      {
          var allNodes = new ArrayList&lt;&gt;(toSort);
          
          toSort.clear();
          for (var node : allNodes) {
              if (!toSort.contains(node)) {
                  add(node, toSort);
              }
          }
      }
  
      static void add(Node node, List&lt;Node&gt; toAdd)
      {
          toAdd.add(node);
          if (!node.dependants().isEmpty()) {
              for (Node dependant : node.dependants()) {
                  toAdd.remove(dependant);
                  add(dependant, toAdd);
              }
          }
      }
  }
  </code></pre>
  <p>So this is called topological order, when a element depends on the other, the other element should be iterated first. In this example the correct order is C B A.</p>
  <p>But I have come with an issue: What if there are bad Nodes that depend on each other? E.g. if A depends on B and B depends on A.
  A StackOverFlowError is thrown because the #add method would be called forever.</p>
  <p>To fix this, I could just loop through the list and remove these nodes that explicitly depend on each other before sorting, but what if the nodes aren't explicitly depending on each other on a scenario like this:</p>
  <p>C depends on A, B depends on C, A depends on B.</p>
  <p>This would also throw a StackOverFlow because: C needs to be after A in the list, but A needs to be after B, and since B depends on C they would just loop forever trying to see who should be first.</p>
  <p>How would I identify and remove these bad nodes from the list?</p>