C 空结构链表
当这是一个空结构时,如何链接链表,我将给出一个示例C 空结构链表,c,linked-list,C,Linked List,当这是一个空结构时,如何链接链表,我将给出一个示例 struct tmpList *addToken2TmpList(struct tmpList *headTmpList, char *token) { struct tmpList *tokenNode = (struct tmpList *)malloc(sizeof(struct tmpList)); tokenNode->data = token; tokenNode->next = NULL;
struct tmpList *addToken2TmpList(struct tmpList *headTmpList, char *token)
{
struct tmpList *tokenNode = (struct tmpList *)malloc(sizeof(struct tmpList));
tokenNode->data = token;
tokenNode->next = NULL;
return cocatenateNodes((struct tmpList *)tokenNode, (struct tmpList *)headTmpList);
}
void *cocatenateNodes(void *node, void *headNode)
{
void *tmp = headNode;
if (headNode == NULL)
{
headNode = node;
}
else
{
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = node;
}
return headNode;
}
编译失败,因为它无法识别tmp->next,如何修复它?这无法工作,因为void不包含任何next成员
必须使用节点结构struct tmpList*访问任何成员。
处理列表操作的函数应该在签名中使用prope节点类型,以获得某种类型安全性。
如果确实希望在签名中使用void*,则必须在函数中强制转换指向struct tmpList*的指针。
否则您将无法访问成员。您应该将tmp转换为tmpList*。写下这样的话:
((struct tmpList*)tmp)->next = node;
但是,如果您想使用void类型,这意味着您的headNode变量应该是任何类型,并且您需要为函数提供一个参数,以了解您想要访问的结构类型并正确地强制转换它。您只需将CoCateNode更改为使用struct tmpList*而不是void*。您可以在AddToken2TempList中删除几个不必要的强制转换
为什么要处理void*而不是struct tmpList*?必须在cast的帮助下,在引用void指针时告诉编译器实际的结构。空白只是一个指针。你能把tmplist的定义贴出来吗?你为什么要把它当作void*?
struct tmpNode *cocatenateNodes(struct tmpNode *node, struct tmpNode *headNode);
struct tmpList *addToken2TmpList(struct tmpList *headTmpList, char *token)
{
struct tmpList *tokenNode = malloc(sizeof(struct tmpList));
tokenNode->data = token;
tokenNode->next = NULL;
return cocatenateNodes(tokenNode, headTmpList);
}
struct tmpNode *cocatenateNodes(struct tmpNode *node, struct tmpNode *headNode)
{
struct tmpNode *tmp = headNode;
if (headNode == NULL)
{
headNode = node;
}
else
{
while (tmp->next != NULL)
{
tmp = tmp->next;
}
tmp->next = node;
}
return headNode;
}