【问题标题】:in this function correct pointer not returned to the calling function在这个函数中正确的指针没有返回到调用函数
【发布时间】: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


【解决方案1】:

第一个错误

head=temp->next;

由于head 是本地参数,因此此分配会更改此本地参数。你需要改变传递给函数的指针,所以你需要你的代码是:

void delete_from_key(node **head, int key)
    //...
    *head=temp->next;
    //...

第二个错误

new = new->next;

类似的问题。 new 是一个局部变量。您正在更改局部变量,而不是更改列表中的指针。

如果search_key确实返回了指向你需要的键之前的节点的指针

temp = new->next;
new->next = new->next->next;
free(temp);

【讨论】:

    【解决方案2】:

    您需要更新前一个节点的 next 以及它的 next 正在被删除。

    prev_node=search_key(head, key);//search_key returns pointer to the node just before the node holding the key.
    
    if(prev_node!= NULL)
    {
        // prev_node->next is the one that needs to be deleted
        temp = prev_node->next; 
    
        //Make the prev node point to the next node of the one that's getting deleted
        prev_node->next = temp->next; 
    
        free(temp);
        return;
    }
    

    【讨论】:

    • 我更新了搜索功能但忘记更新评论了。我已经编辑过了。谢谢!
    猜你喜欢
    • 2020-01-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    相关资源
    最近更新 更多