同一节点中的不同结构体链表 C

Joh*_*oey 1 c struct adt

我的作业有点困难,想知道是否有人可以指出我正确的道路。

我希望创建一个支持使用不同节点的链表,因为我需要使用不同的数据集。

目前我正在使用三个结构:

struct equipment_data {
    char EquipID[4+1]; /* 4 Max */
    char EquipName[31+1]; /* 31 Max */
    unsigned TotalNumber;
};

struct member_data {
    unsigned MemberID;
    char LastName[31+1]; /* 31 Max */
    char FirstName[31+1]; /* 31 Max */
};

struct loan_data {
    unsigned MemberID;
    char EquipID[4+1]; /* 4 Max */
    unsigned Number;
};
Run Code Online (Sandbox Code Playgroud)

我需要以某种方式在同一节点内使用它。

struct ets {
    struct node *equipment_data;
    struct node *member_data;
    struct node *loan_data;
    unsigned equip_count;
    unsigned member_count;
    unsigned loan_count;
};

struct node {
    void *data;
    struct node *next;
};
Run Code Online (Sandbox Code Playgroud)

看来我需要创建一个ADT链表。能否请你帮忙?谢谢!

Kar*_*bat 5

我将为您需要支持的类型创建结构,然后在链表节点中创建一个带有类型指示符的联合:

typedef struct { int a, b, c;    } Type1;
typedef struct { char buf[80];   } Type2;
typedef struct { int a; float b; } Type3;

typedef union {
    Type1 t1,
    Type2 t2,
    Type3 t3;
} Anytype;

typedef struct node {
    int thistype;   // 1 for type1, 2 for type2 etc.
    Anytype data;
    struct node *next;
} Listnode;
Run Code Online (Sandbox Code Playgroud)

只要确保您thistype在每个中设置正确Listnode即可。

Listnode *node = malloc(sizeof(Listnode));
node->thistype = 1;  // example: Type1, the 3 ints
node->t1.a = 1;
node->t1.b = 2;
node->t1.c = 3;
node->next = someothernode;
Run Code Online (Sandbox Code Playgroud)

您可以使用 aswitch来访问数据:

Listnode *node;
switch (node->thistype) {
    case 1: 
        // do stuff with node->t1.a, node->t1.b, node->t1.c
        break
    case 2:
        // do stuff with node->t2.buf
        break;
    case 3:
        // do stuff with node->t3.a, node.t3.b
        break
}
Run Code Online (Sandbox Code Playgroud)