Search code examples
cprintftreenode

C: how to print a list in reverse order?


I am trying to print a list of tree_nodes in reverse order:

Current prompt example: /helloFellow/hello/root / >

Desired result: root/hello/helloFellow / >

What is a way to do this efficiently?

// *prints the prompt (e.g. /bar/baz/ >) in every iteration of the main loop
// *show all directories on the path in correct order
void show_prompt(struct tree_node *cwd) {
    struct tree_node *parDir = cwd->parent;
    struct tree_node *originalDir = cwd;

    while (cwd->parent != NULL) {
        printf("/");
        printf("%s", cwd->parent->string_buffer);
        cwd = cwd->parent;
    }
    cwd = originalDir;
    printf("/ >");
}

Solution

  • You could use recursion:

    void print_path( struct tree_node * cwd ) {
        if ( cwd->parent != NULL )
            print_path( cwd->parent );
        printf( "%s/", cwd->string_buffer );
    }