简短的回答是:你不能。
如果您希望“节点”成为两个不同列表的成员,则必须从一开始就考虑到这一点来设计列表和节点结构(例如,通过为数据和实际列表节点设置单独的结构)。
您可以做的是将节点从现有列表复制到新列表。这意味着您必须创建一个全新的struct resourceList
节点,从中复制它resource
,然后将新节点添加到列表中。
也许像
if (list == NULL)
{
// Create a new node
list = malloc(sizeof *list);
// Copy the data from another node
*list = *resource;
// No nodes after this one
list->next = NULL;
// Make the new node the head of the list
p->resourceListPtr = list;
}
[省略错误检查]
如果您希望多个列表中的节点共享数据,那么您需要在设计列表时考虑到这一点,如前所述。一种好方法是为列表、节点和数据创建单独的结构。
例如,您可以有类似的东西
struct resource
{
// The actual resource data
};
// Node in list
struct resourceNode
{
struct resource *data; // Pointer to the data
struct resourceNode *next; // Next node in list
};
struct resourceList
{
struct resourceNode *head;
struct resourceNode *tail;
};
使用上述结构,很容易拥有多个具有唯一节点的列表,但节点中的数据可以在列表之间共享。
简单的例子:
// Create two lists
struct resourceList list1;
struct resourceList list2;
// TODO: Initialization of the lists
struct resource my_resource;
// TODO: Initialization of my_resource ...
// Add the same resource to both lists
resource_list_add(&list1, &my_resource);
resource_list_add(&list2, &my_resource);
如果更改资源数据,则两个列表都会更改。
将一个列表中的数据添加到另一个列表中也很容易:
struct resourceNode *node1 = list1.head;
resource_list_add(&list2, node1->data);