I have a linked list contains 3 nodes like the image shown:
There is a head pointe
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.