Topological Sort using Iteration instead of Recursion

Viewed 1367

I initially had this recursive solution for a topological sort:

void dfs(int v, bool visited[], node* adjList[], std::stack<int> &myStack) {
    visited[v] = true;
    node* curr = adjList[v];

    while (curr != NULL) {
        if(!visited[curr->val]) {
            dfs(curr->val, visited, adjList, myStack);
        }
        curr = curr->next;
    }
    myStack.push(v);
}

and it seemed to work for my purposes. But I'm having trouble translating it into an iterative solution. This is my attempt:

void dfs(int v, bool visited[], node* adjList[], std::stack<int> &myStack) {
    std::stack<int> recursion;
    visited[v] = true;

    recursion.push(v);

    while( !recursion.empty() ) {
        v = recursion.top();
        recursion.pop();
        node* curr = adjList[v];

        myStack.push(v);

        while (curr != NULL) {
            if(!visited[curr->val]) {
                visited[curr->val] = true;
                recursion.push(curr->val);
            }
            curr = curr->next;
        }
    }
}

But the ordering is completely messed up! I think it might be due to the positioning of my myStack.push(v), but I don't know how to approach this. Any help would be appreciated it.

1 Answers
Related