问题描述
我必须用C语言编写一个链表程序,其中每个节点本身的成员数量是可变的.节点内的成员可以是相同或不同的数据类型.任何想法将不胜感激...
Hi,
i have to write a linked list program in C, in which the number of members within each node itself is variable.The members within node could be of same or different data types. Any ideas would be greatly appreciated...
推荐答案
<ul><li>a pointer of the actual data structure, as <code>void *</code>.</li>
<li>a integer value representing the actual type of the data.</li>
(当然,您还必须存储一个指向列表下一项的指针...)
例如:
(of course you''ve also to store a pointer to the next item of the list...)
for instance:
/* data structs, i.e. node types */
typedef struct tagPoint
{
int x;
int y;
}Point;
typedef struct tagUser
{
const char * name;
int age;
/*..*/
} User;
/*... other data types...*/
typedef enum TagNodeType
{
ePoint,
eUser,
/*...*/
eNODETYPES
} NodeType;
typedef struct TagListItem
{
NodeType nt;
void * pData;
struct TagListItem * pNext;
} ListItem;
然后实现addListItem
函数,该函数接受指向实际数据的指针和代表数据类型的值.
在检索数据时,您必须检查nt
字段,以便正确地投射pData
指针.
:)
Then implement a addListItem
function accepting a pointer to actual data and a value representing the data type.
On retrieving data you''ve to check the nt
field in order to properly cast the pData
pointer.
:)
这篇关于每个节点中成员数量动态可变的链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!