Remove all nodes in linked list

前端 未结 4 1182
清酒与你
清酒与你 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: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 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.

提交回复
热议问题