c - 如何在 C 中存储链表列表?

标签 c data-structures linked-list

考虑 C 中的多个 Linked List。如下代码所示:

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

我想有很多这个链表。我怎样才能拥有它?例如:

1, 2, 3

1, 5, 6

1, 3, 5, 7

这是我的链接列表的三个实例,我需要将它们及其大小存储在列表中。

所以,我不知道如何拥有链表的多个实例并将它们存储到一个列表中(我应该使用另一个链表吗?)。

最佳答案

您的struct path 是一个整数链表。如果你想要一个路径列表,你也可以定义它:

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;
};

要使用任何一种链表,您通常需要定义函数来分配/释放/操作/查询列表。所以你可能有

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; }

这允许您创建上面的示例:

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)))

关于c - 如何在 C 中存储链表列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49381566/

相关文章:

c - Strtol()函数基本c

c - C 中的意外输出(树的遍历)

python - 如何生成排列列表列表

java - 删除列表元素 - 我在 Java 中实现最佳性能的方法

java - 在字符串链表的链表中查找重复项的最有效方法 - java

c - 警告 : extra tokens at end of#include directive

c - 通过套接字发送图像的最佳方法?

c - 开关盒基本型

c - 递归添加数字序列

java - java中的原始数据类型是如何定义/编写的?