【问题标题】:Trying to insert node in a singly linked list after a certain position but it inserts it before尝试在某个位置之后将节点插入单链表中,但它在之前插入
【发布时间】:2019-12-11 13:50:55
【问题描述】:

试图在链表中的某个位置之后插入一个节点,但它在之前插入了它。 尝试修改它,它仍然在之前添加它或者只是删除链表的其余部分

Destination *insertAfter(Destination *head, Destination *node, char *key)
{
    Destination *ptr;
    Destination *previous = NULL;
    Destination *newNode = (Destination*)malloc(sizeof(Destination));
    if(head == NULL)
    {
         return node;
    }
    for(ptr =head; ptr != NULL; ptr = ptr-> next)
    {
       if(strcmp(ptr->code, key) == 0)
       {
          node->next = ptr;

        if(previous != NULL)
          {
            previous->next = node;
            return head;
          }
        else
        {
            return node;
        }
    }
    previous = ptr;
   }
  previous->next = node;
  return head;

}

【问题讨论】:

  • @HenriPrudhomme 所以本质上是用户输入一个字符串,然后搜索链表并在他们输入的字符串之后输入
  • 我有答案了,给我15分钟打出来

标签: c linked-list nodes singly-linked-list


【解决方案1】:

你几乎拥有它。您遇到的问题是,一旦找到字符串匹配项,您的代码就会丢失指向下一个节点的指针。

Destination *insertAfter(Destination *head, Destination *node, char *key)
{
    Destination *matchNode;

    if(head == NULL)
    {
        head = node;
    }
    else
    {
        for(matchNode = head; matchNode != NULL; matchNode = matchNode->next)
        {
            //check for match
            if(strcomp(matchNode->code, key) == 0)
            {
                //Set remaining list to what follows the inserted node
                node->next = matchNode->next;

                //Set new node as next node to front half of list
                matchNode->next = node;
            }
        }
    }
    return *head;
}

除了您提供的内容之外,我没有添加任何额外的安全检查,但您还需要检查是否已分配头和节点。

我希望这会有所帮助。我无法测试这是否与您的代码一起编译,因此如果您从中得到任何东西,您需要知道在将匹配索引分配给要插入的节点之前,您必须保存列表的末尾,然后才您可以将列表的末尾附加到您插入的节点吗?

如果这不起作用,请告诉我。

【讨论】:

    猜你喜欢
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多