尝试在某个位置之后将节点插入单链表中,但它插入之前

Trying to insert node in a singly linked list after a certain position but it inserts it before

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

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;

}

你快搞定了。您遇到的问题是,一旦找到字符串匹配,您的代码就会失去对指向下一个节点的指针的跟踪。

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

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

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

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