同一节点中的不同结构链接列表C.

时间:2015-01-23 10:31:10

标签: 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;
};

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

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

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

4 个答案:

答案 0 :(得分:3)

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

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;

请确保在每个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;

您可以使用switch访问数据:

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
}

答案 1 :(得分:1)

您应该创建一个指向各种结构的节点。

struct node {
struct equipment_data *eq_data; // This pointers to equipment struct
struct member_data * me_data; // ......
struct load_data * lo_data; // .....
unsigned equip_count;
unsigned member_count;
unsigned loan_count;
struct node* next_node; // this points to the next node in the 

};

答案 2 :(得分:1)

您可以将结构ets的变量放在struct node中。

struct node {
void *data;
struct ets *var;
struct node *next;
};

现在您可以访问所有结构。

答案 3 :(得分:1)

枚举您要存储的数据类型

typedef enum type{ equipment, member,loan,ets} type;    
typedef struct lnk_lst
{
  type data_type;
  void* data;
  struct lnk_lst* next;
} lnk_lst ;

初始化将类似于

equipment_data e1;
lnk_lst* node=(lnk_lst*)malloc(sizeof(lnk_lst));
node->data_type=equipment;

//if created dynamically
   node->data=malloc(sizeof(equipment_data));
//just to point existing equipment_data
   node->data=(void*)(&e1);

node->next=NULL;

评估列表就像

switch(node->data_type)
{
 case equipment:
   printf("%d",((equipment_data*)(node->data))->TotalNumber);
   puts( ((equipment_data*)(node->data))->EquipID );
   puts( ((equipment_data*)(node->data))->EquipName );
 case member:
   //code to read member_data
 case loan:
   //code to read loan_data
 case ets:
   //code to read ets
 }