I have implemented this pseudocode in my program to check if a directed graph is acyclic:
L ← Empty list that will contain the sorted elements
S ← Set of all nodes with no incoming edges
while S is non-empty do
remove a node n from S
add n to tail of L
for each node m with an edge e from n to m do
remove edge e from the graph
if m has no other incoming edges then
insert m into S
if graph has edges then
return error (graph has at least one cycle)
else
return L (a topologically sorted order)
This works great, but I also need to output the actual cycle if the graph isn't acyclic. Is it possible to do this "inside" this code, or do I need to change my algorithm completely? I have tried to search for a solution, and I found this answer (Printing(not detecting) cycle with topological sort) but I can't understand how to actually do this. Does anyone have some pseudocode that could help me?