一般情况下,您需要在struct Node 中添加类型标签,以便跟踪存储在各个节点中的数据类型。
对于存储数据,您可以使用 void 指针,也可以使用联合。如果您使用 void 指针,您将需要在访问数据时进行强制转换。如果你使用联合,每个节点最终都会使用与最大联合成员大小相对应的内存。
这是一个简单的例子使用空指针:
#include <stdio.h>
#include <stdlib.h>
enum ListType
{
INT = 0,
FLOAT,
CHAR,
STRING,
};
struct Node
{
struct Node *next;
enum ListType type;
void *data;
};
void printNode(struct Node *p)
{
switch (p->type)
{
case INT:
printf("%d ", *((int*)p->data));
break;
case FLOAT:
printf("%f ", *((float*)p->data));
break;
case CHAR:
printf("%c ", *((char*)p->data));
break;
case STRING:
printf("%s ", (char*)p->data);
break;
default:
printf("ERROR ");
break;
}
}
void printList(struct Node *p)
{
while(p)
{
printNode(p);
p = p->next;
}
}
void freeListData(struct Node *p)
{
while(p)
{
free(p->data);
p = p->next;
}
}
int main(void) {
// Build the list manually to illustrate the printing
struct Node N1;
struct Node N2;
N1.type = FLOAT;
N1.data = malloc(sizeof(float));
*((float*)N1.data) = 3.14;
N1.next = &N2;
N2.type = INT;
N2.data = malloc(sizeof(int));
*((int*)N2.data) = 100;
N2.next = NULL;
// .. more nodes
printList(&N1);
freeListData(&N1);
return 0;
}
输出:
3.140000 100
这是一个使用联合的例子:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
enum ListType
{
INT = 0,
FLOAT,
CHAR,
STRING,
};
union ListData
{
int d;
float f;
char c;
char *str; // Memory for the string must be malloc'ed
};
struct Node
{
struct Node *next;
enum ListType type;
union ListData data;
};
void printNode(struct Node *p)
{
switch (p->type)
{
case INT:
printf("%d ", p->data.d);
break;
case FLOAT:
printf("%f ", p->data.f);
break;
case CHAR:
printf("%c ", p->data.c);
break;
case STRING:
printf("%s ", p->data.str);
break;
default:
printf("ERROR ");
break;
}
}
void printList(struct Node *p)
{
while(p)
{
printNode(p);
p = p->next;
}
}
void freeListStrings(struct Node *p)
{
while(p)
{
if (p->type == STRING) free(p->data.str);
p = p->next;
}
}
int main(void) {
// Build the list manually to illustrate the printing
struct Node N1;
struct Node N2;
struct Node N3;
N1.type = FLOAT;
N1.data.f = 3.14;
N1.next = &N2;
N2.type = INT;
N2.data.d = 100;
N2.next = &N3;
N3.type = STRING;
N3.data.str = malloc(sizeof "Hello World");
strcpy(N3.data.str, "Hello World");
N3.next = NULL;
// .. more nodes
printList(&N1);
freeListStrings(&N1);
return 0;
}
输出:
3.140000 100 Hello World