每个节点中成员数量动态可变的链接列表 [英] Linked list with dynamically variable number of members within each node
问题描述
我必须用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...
推荐答案
如果您拥有一组有限的可能节点类型,则可以为每个节点定义一个struct
在每个节点中键入和存储
If you''ve a finite set of possible node type, then you may define astruct
for each node type, and store, in every node both
<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.
:)
您是否在谈论B树?
实际上,在C语言中,任何可以实现这种要求的概念都可以.为简化起见,让我们考虑节点内的成员可以是相同的数据类型,例如int.因此,可能存在一些具有int的成员和一些具有整数数组的成员.
Actually any concept in C, that could implement this sort of requirement is fine. To simplify let us consider that members within a node can be of same data type for example int. So there can be some members with int and some with integer array.
这篇关于每个节点中成员数量动态可变的链接列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!