【问题标题】:void struct linked list [closed]void struct链表[关闭]
【发布时间】:2018-04-05 11:46:47
【问题描述】:

当这是一个 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->next,如何解决?

【问题讨论】:

  • 为什么要处理void*而不是struct tmpList*
  • 在引用 void 指针时,您必须在强制转换的帮助下告诉编译器实际结构。 void 只是一个指针。
  • 能否请您发布tmplist 的定义?又为什么要处理成void*

标签: c linked-list


【解决方案1】:

这不能工作,因为void 不包含任何成员next

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

【讨论】:

    【解决方案2】:

    您应该将 tmp 转换为 tmpList*。并写出类似的东西:

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

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

    【讨论】:

      【解决方案3】:

      您可以简单地将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;
      }
      

      【讨论】:

        猜你喜欢
        • 2021-10-21
        • 2017-10-26
        • 1970-01-01
        • 2012-05-06
        • 2020-06-24
        • 2013-03-05
        • 2014-04-04
        • 2013-09-23
        • 1970-01-01
        相关资源
        最近更新 更多