Saeed Rahmani
Saeed Rahmani

Reputation: 652

How to store a list of linked lists in C?

Consider a number of Linked List in C. As shown in the following code:

struct path {
int node;
struct path *next;
};

I want to have a lot of this linked list. How can I have it? For example:

1, 2, 3

1, 5, 6

1, 3, 5, 7

These are three instances of my Linked list and I need to store them with their size in a list.

So, I do not know how to I can have many instances of the Linked list and store them into a list (Should I use another Linked list?).

Upvotes: 1

Views: 1139

Answers (1)

Chris Dodd
Chris Dodd

Reputation: 126253

Your struct path is a linked list of integers. If you want a list of paths, you can define that too:

struct path_list {
    struct path *path;
    int path_size;  /* optional: a place to store the size of "path" rather than recomputing it all the time */
    struct path_list *next;
};

To use any kind of linked list, you generally want to define functions to allocate/free/manipulate/query lists. So you might have

struct path *new_path_el(int node, struct path *next) {
    struct path *rv = malloc(sizeof(struct path));
    rv->node = node;
    rv->next = next;
    return rv; }
int path_size(struct path *path) {
    int rv = 0;
    while (path) {
        ++rv;
        path = path->next; }
    return rv; }
struct path_list *new_path_list_el(struct path *path, struct path_list *next) {
    struct path_list *rv = malloc(sizeof(struct path_list));
    rv->path = path;
    rv->path_size = path_size(path);
    rv->next = next;
    return rv; }

Which allows you to create your example above:

new_path_list_el(
    new_path_el(1, new_path_el(2, new_path_el(3, 0))),
  new_path_list_el(
      new_path_el(1, new_path_el(5, new_path_el(6, 0))),
    new_path_list_el(
        new_path_el(1, new_path_el(3, new_path_el(5, new_path_el(7, 0)))), 0)))

Upvotes: 1

Related Questions