Re-implemented TopologicalSort().