简体   繁体   中英

How to traverse a multi-level linked list?

I'm writing a C program to save data on managers and employees in a company.

The structure is a multi-level linked list. Each manager can contain inside managers and employees.

Here is the structure

typedef struct Node {
    char* name;
    NODE* next;
    NODE* down;
        NODE* parent; 
    int is_manager;
} NODE;

In my program I want to traverse the structure so I can find a specific employee, add to them data, remove them etc.

the add/remove functions are easy - but I'm stuck on how to traverse and search in this structure.

Thank you in advance for any kind of help.

Expanding on my example:

void print_node(NODE *node)
{
    // Tread node as the head of a list, and iterate over that list the "normal" way
    while (node)
    {
        // But also go down the "tree"...
        if (node->down)
        {
            print_node(node->down);
        }

        // Print the name
        printf("%s ", node->name);

        // And go to the next node in the list
        node = node->next;
    }
}

By following the advice by jdweng it shouldn't have been to hard to figure this out yourself. Draw it all out using pen and paper, and follow along as you "manually" print that tree.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM