首页 文章

删除链接列表中的所有节点

提问于
浏览
0

我有一个链表包含3个节点,如图所示:
enter image description here

有一个头指针和temp1指针指向列表的前面,尾点指向列表的末尾 .

我想删除所有节点,并将其更改回其原始初始形式(tail = NULL,head = first_node,但第一个节点在数据和下一个字段中没有任何值) .

因为我想开始在其中添加一些新值 . 要删除所有这些数据,此代码是否会删除此链接列表中的节点,并留下第一个节点,数据和下一个字段中没有值?

这段代码在C中:

while(temp1!=tail)
{
    temp1 = temp1->next;
    if(temp1->next == tail)
    {
        tail=temp1;
        temp1 = temp1->next;
        free(temp1);    
    }
}

但那么,这是否意味着只删除最后一个节点?有没有办法删除除第一个节点以外的所有节点?

4 回答

  • 0

    要删除除第一个节点以外的所有节点,您可以尝试下面的代码 .

    temp1 = head->next;
    while(temp1!=NULL) // as I am considering tail->next = NULL
    {   
        head->next = temp1->next;
        temp1->next = NULL;
        free(temp1);
        temp1 = head->next;
    }
    

    这将删除除第一个节点之外的所有节点 . 但是第一个节点的数据将保持不变 .

  • -1
    temp1 = head->next;
    
    while(temp1!=NULL) // as I am considering tail->next = NULL
    {
        head->next = temp1->next;
        temp1->next = NULL;
        free(temp1);
        temp1 = head->next;
    }
    

    如果是这样的话,这个逻辑会更正确 .

    声明之后

    free(temp1);
    

    添加条件

    if (head -> next != NULL)
        temp1 = head->next;
    

    Since after deleting the last node there is no point in reassigning the address of head pointer to temp1.

  • 5

    免责声明:我认为它仅用于学习目的,在实际场景中,您将使用std :: list <>或类似的容器 .

    对于单链表,你可以放弃所有这些负担让stdlib管理指针:

    class Node {
        std::unique_ptr<Node> next;
    };
    

    您可以安全地使用 .reset() 方法对列表进行操作:

    给定current_ptr,由* this管理的指针按以下顺序执行以下操作:保存当前指针的副本old_ptr = current_ptr用参数current_ptr = ptr覆盖当前指针如果旧指针非空,删除以前管理的对象if(old_ptr!= nullptr)get_deleter()(old_ptr) .

    来自http://en.cppreference.com/w/cpp/memory/unique_ptr/reset .

    这就是删除时你会做的事情 . 我相信您也可以使用unique_ptr::swap()来轻松操作您的节点 .

  • 5

    而不是 free ,C使用delete函数 .

    检查link以了解链接列表上所有类型的操作(包括递归或迭代删除) .

相关问题