As the textbook shown, a linkedlist is good for those situations where it frequently inserts or deletes since it costs O(1) for these operations. However, a node of linkedlist doesnot contains any pointer that points to the previous node. So if I need to delete a specific node, I may have to find the previous node and change the information of its next pointer, which costs O(n). Or, if not, the reference for the next node will be affected. I don't know how to solve this problem.
// These operations have to find the previous node of the position, so it costs O(n).
node* erase(node* head, int pos);
node* erase(node* node_to_delete);
// This operation costs O(1), but it affect the validation of the reference of the next node.
node* erase(node* position) {
if (position == _last)
return _last;
auto tmp = position -> next;
position -> val = position -> next -> val;
position -> next = position -> next -> next;
delete tmp;
if (tmp == _last)
_last = position;
_size--;
return position;
}
I expect insert or delete the node in O(1).
There's no reason why you have to start with a pointer to the node itself. You can work with pointers to preceding nodes.