Remove all nodes in linked list

前端 未结 4 1132
清酒与你
清酒与你 2021-01-29 06:03

I have a linked list contains 3 nodes like the image shown: \"enter

There is a head pointe

相关标签:
4条回答
  • 2021-01-29 06:16

    To delete all nodes except the first node, you can try below code.

    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;
    }
    

    This will delete all nodes except first one. But the data with the first node will remain as it is.

    0 讨论(0)
  • 2021-01-29 06:23

    Instead of free, C++ uses delete function.

    Check the link to have deep knowledge about all kind of operations(including recursive or iterative delete) on linked lists.

    0 讨论(0)
  • 2021-01-29 06:31
    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;
    }
    

    The logic for this would be more correct if it is this way.

    After the statement

    free(temp1);
    

    Add the condition

    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.

    0 讨论(0)
  • 2021-01-29 06:33

    Disclaimer: I assume it's only for learning purposes and in real-world scenario you would use std::list<> or similar container.

    For single-linked list, you can just drop all this burden an let the stdlib manage the pointers:

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

    You can safely use .reset() method to make operations on the list:

    Given current_ptr, the pointer that was managed by *this, performs the following actions, in this order:

    • Saves a copy of the current pointer old_ptr = current_ptr
    • Overwrites the current pointer with the argument current_ptr = ptr
    • If the old pointer was non-empty, deletes the previously managed object if(old_ptr != nullptr) get_deleter()(old_ptr).

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

    And that's pretty much what you would do when deleting. I believe you can also use unique_ptr::swap(), to easily manipulate your nodes.

    0 讨论(0)
提交回复
热议问题