【发布时间】:2019-08-16 10:51:53
【问题描述】:
问题是当我在删除节点后打印列表时,打印功能会打印 0 代替已删除的节点.....但我希望它什么也不打印。
// the function call is delete_from_key(&head,i);
//node is struct linked_list
void delete_from_key(node *head, int key)
{
node *new, *temp;
if(head == NULL)
{
printf("nothing to delete . the list is empty.\n");
return;
}
else if(head->num == key)
{
temp=head;
head=temp->next;
free(temp);
return;
}
new=search_key(head, key);//search_key returns pointer node holding the key.
if(new != NULL)
{
temp = new;
new = new->next;
free(temp);
return;
}
}
示例:
列表是1-> 2-> 3-> 4-> 5->
如果我用键 2 调用此函数
预期的输出是1-> 3-> 4-> 5->
相反,实际输出是1-> 0-> 3-> 4-> 5->
【问题讨论】:
-
不要垃圾邮件标签。
new是 C++ 中的关键字,因此不可能成为 C++ 程序的一部分。标签是为了正确定义问题的范围,而不是为了获得曝光。 -
temp = new->next; //temp points to node holding the key...new->next = temp->next; //new->next points to node which is after the node holding the key....free(temp); -
当
new不是NULL时,您错过了将new的上一个指针设置为new的下一个指针。您必须跟踪要删除的节点的前一个指针。 -
@sameerkn 不在 cmets 中回答。
-
你已经在第一个 if 中检查了 head 是否为 NULL,所以你不需要在第二个中再次检查...
标签: c pointers scope dynamic-memory-allocation singly-linked-list