Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/140.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 在键处插入链表函数被某些参数卡住了?_C++_Linked List - Fatal编程技术网

C++ 在键处插入链表函数被某些参数卡住了?

C++ 在键处插入链表函数被某些参数卡住了?,c++,linked-list,C++,Linked List,在包含值“key”的节点之后插入一个新节点,在给定的链表中具有值“newKey”的节点。如果找不到钥匙,就不会发生任何事情 但是,当我从main运行此函数时,其值不在我的链接列表中,main函数将停止,并且在调用insert\u after后不会完成任何操作。为什么会发生这种情况 我的推理是,如果键在链表中不存在,最终temp将设置为NULL,这将中断“while”循环,并跳过第二个“if”循环。这些环路中有一个没有断开吗 如果列表有多个节点且head->next的键不匹配,则此while循环无

在包含值“key”的节点之后插入一个新节点,在给定的链表中具有值“newKey”的节点。如果找不到钥匙,就不会发生任何事情

但是,当我从main运行此函数时,其值不在我的链接列表中,main函数将停止,并且在调用insert\u after后不会完成任何操作。为什么会发生这种情况


我的推理是,如果键在链表中不存在,最终temp将设置为NULL,这将中断“while”循环,并跳过第二个“if”循环。这些环路中有一个没有断开吗

如果列表有多个节点且
head->next
的键不匹配,则此while循环无限循环:

struct Node {
  int key;
  Node* next;
}; 

void insert_after(Node* head, int key, int newKey )
{

  if(head != NULL){
    Node* temp = head;          
    while(temp!=NULL && key != temp->key){
        temp = head->next;
    }

    if(temp != NULL){
        Node* afterInserted = temp->next;
        Node* inserted = new Node;
        inserted->key = newKey;
        inserted->next = afterInserted;
        temp->next = inserted;
    }
  }

}
您想将
temp->next
分配给
temp
,而不是
head->next
。 因此,代码变为:

 while(temp!=NULL && key != temp->key){
        temp = head->next;
    }

如果head为null(即空链表),那么我不希望发生任何事情,这就是为什么我没有包含else语句的原因。第二个if也一样,因为只有在找不到值时temp才应该为null,在这种情况下不应该发生任何事情。你所说的需求未被明确是什么意思?好吧,你是对的,需求是有意义的。不过,为了减少缩进,我将它写成
if(head==NULL){return;}
。事实上,你只需要一个空校验,而不是两个,因为第二个条件是第一个条件的超集。。。这完全有道理。谢谢你的评论,我不知道我是怎么错过的。
 while(temp!=NULL && key != temp->key){
        temp = temp->next;
    }