void struct链表

时间:2018-04-05 11:46:47

标签: c linked-list

如果这是一个void结构,我如何链接一个链表,我将举一个例子,

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->接下来,我该如何解决?

3 个答案:

答案 0 :(得分:0)

这不起作用,因为void不包含任何成员next

您必须使用节点结构struct tmpList *来访问任何成员。 处理列表操作的函数应该使用签名中的prope节点类型来获得某种类型的安全性。 如果您确实想在签名中使用void *,则必须将指针强制转换为函数内的(struct tmpList *)。 否则您将无法访问成员。

答案 1 :(得分:0)

您应该将tmp转换为tmpList *。写下这样的东西:

((struct tmpList*)tmp)->next = node;

但是如果你想使用void类型,这意味着你的headNode变量应该是任何类型的,你需要给函数一个参数,以便知道你想要访问的结构类型并将其转换为正常。

答案 2 :(得分:0)

您只需更改cocatenateNodes即可使用struct tmpList *代替void *。您可以在addToken2TmpList中删除多个不必要的演员表。

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;
}