【问题标题】:How can I add a new node to the begining of my linked list?如何将新节点添加到链表的开头?
【发布时间】:2020-05-01 05:13:35
【问题描述】:

我正在尝试创建一个将节点添加到链接列表开头的函数。我已经创建了新节点并成功地将新节点指向了链表中的原始标题。但是我不确定如何将我的新节点设置为链表的标题。

void insert_node(BURGER* header)
{
    BURGER* tp1;

    printf("Enter the details of record to be inserted in the format as\n");
    printf("<name>\n<popularity>\n");
    scanf_s("%s", &name, sizeof(name));
    scanf("%d", &popular);

    tp1 = make_node(name, popular);
    tp1->next = header;
    header = tp1;
    //printf("%d", tp1->next->popularity);

    printf("\n\n New record inserted at the start of the List\n");
}

亲切的问候

【问题讨论】:

  • 这能回答你的问题吗? Adding to the front of a Linked List in C
  • 如果这没有帮助建议进行搜索。 Stack Overflow 和整个互联网上有无数的帖子解释了不同的方法。
  • OT:这里的正确术语是“head”,而不是“header”。

标签: c


【解决方案1】:

我认为您的思考过程是正确的。但是,该代码不起作用,因为您尝试将新节点设置为标头,而这不起作用,因为BURGER * header 是指向标头的指针的副本。所以你可以这样做:

void insert_node(BURGER** header)
{
    BURGER* tp1;

    printf("Enter the details of record to be inserted in the format as\n");
    printf("<name>\n<popularity>\n");
    scanf_s("%s", &name, sizeof(name));
    scanf("%d", &popular);

    tp1 = make_node(name, popular);
    tp1->next = *header;
    *header = tp1;
    //printf("%d", tp1->next->popularity);

    printf("\n\n New record inserted at the start of the List\n");
}

这样,你修改了原来的指针,更新了链表的头部。

【讨论】:

    【解决方案2】:

    而不是传递header,传递header的地址。

    // void insert_node(BURGER* header)
    void insert_node(BURGER** header)
    ...
    //tp1->next = header;
    //header = tp1;
    tp1->next = *header;
    *header = tp1;
    

    【讨论】:

      【解决方案3】:

      要使此代码高效,您必须进行某些更改,例如。 您必须将函数的返回类型从 void 更改为 BURGER * 你必须将新节点返回到主函数并分配 它指向指向主函数中链表的指针。 你的代码会是这样的。

      BURGER * insert_node(BURGER* header)
      {
          BURGER* tp1;
      
          printf("Enter the details of record to be inserted in the format as\n");
          printf("<name>\n<popularity>\n");
          scanf_s("%s", &name, sizeof(name));
          scanf("%d", &popular);
      
          tp1 = make_node(name, popular);
          tp1->next = header;
          //printf("%d", tp1->next->popularity);
      
          printf("\n\n New record inserted at the start of the List\n");
      return(tp1);
      }
      

      【讨论】:

        【解决方案4】:

        链表它的第一个节点,所以只需返回tp1

        【讨论】:

          猜你喜欢
          • 2021-06-28
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-22
          • 1970-01-01
          • 2020-02-07
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多