The common technique used to process loops has a set of peaks already visited. Before you push the vertex into the queue / stack, check if it has been visited. If this did not take any action, otherwise start by adding it to the visited set, and then continue the movement schedule.
Stack from top to bottom.
DFS:
empty stack visiting 0: stack: 2, 1, visited: 0 visiting 2: stack: 5, 3, 1 visited: 0, 2 visiting 5: stack: 4, 3, 1 visited: 0, 2, 5 visiting 4: stack: 3, 2, 3, 1 visited: 0, 2, 4, 5 visiting 3: stack: 4, 2, 3, 1 visited: 0, 2, 3, 4, 5 visiting 4: (nothing to do) - stack: 2, 3, 1 visited: 0, 2, 3, 4, 5 visiting 2: (nothing to do) - stack: 3, 1 visited: 0, 2, 3, 4, 5 visiting 3: (nothing to do) - stack: 3, 1 visited: 0, 2, 3, 4, 5 visiting 1: stack: 3, 0 visited: 0, 1, 2, 3, 4, 5 visiting 3: (nothing to do) - stack: 1 visited: 0, 1, 2, 3, 4, 5 visiting 1: (nothing to do) - stack empty visited: 0, 1, 2, 3, 4, 5 DONE
Similarly for BFS.