【问题标题】:Why isn't my delete node function actually deleting the node?为什么我的删除节点功能实际上并未删除节点?
【发布时间】:2019-04-03 02:02:29
【问题描述】:

我正在尝试创建一个更像 C 链表的链表,但它不会永久删除节点。当我运行函数后打印出链表时,节点仍然存在。为什么我的删除节点函数实际上并没有删除节点?

bool removeFromList(int delID, node* &head){

    node* temp = new node;
    node* curr = head;

    while(curr != NULL && curr->id != delID){
        temp = curr;
        curr = curr->next;
    }

    if(curr == NULL){
        cout << delID << " was not in the has table." << endl;
        return false;
    }
    else{
        node* next = curr->next;
        cout << "Node with id " << curr->id << " was deleted." << endl;
        delete curr;
        curr = NULL;
        temp->next = next;

        return true;
    }

}

【问题讨论】:

  • 为什么用new node初始化temp?稍后,您正在为 temp 分配一个值,并且您正在丢失分配给 temp 的内存。
  • ^^^ 简短版本:删除节点应该需要 no 新分配。相关,要正确执行此操作,遍历一个指向指针的指针,从它的值从&amp;head(这将起作用,因为`head 是对真实指针的引用)向下到要删除的节点,使此任务 更干净。

标签: c++ struct linked-list


【解决方案1】:

你需要将 head 分配给列表中的第二个元素

【讨论】:

    【解决方案2】:

    当要移除的元素是列表的第一个元素时,您应该将 head 分配给列表的第二个(如果存在)元素。那就是:

    bool removeFromList(int delID, node* &head){
        //Checking for the front of the list
        if (head != NULL && head->id == delID){
             head = head->next;
             return true;
        }
    
        node* temp; //You don't need to initialize this
        ...//the rest of your code may remains equal
    }
    

    【讨论】:

    • 感谢您的帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-19
    • 2020-05-23
    • 1970-01-01
    • 2017-04-12
    • 2020-04-18
    • 2019-03-27
    相关资源
    最近更新 更多