Consider an implemented struct Node
:
template <class T>
struct Node {
Node<T> * next;
T data;
// Other functions for adding nodes etc...
};
Then a function remove(...)
is given, which takes the parameters 1) reference to pointer to node p
and 2) the data d
to be removed:
template <class T>
void remove(Node<T> *& p, T d) {
if (p != nullptr) {
if (p->data == d) {
Node<T> * temp = p;
p = p->next;
delete temp;
remove(p, d);
}
else {
remove(p->next, d);
};
};
};
Questions
I don't quite understand how this will work. Since temp
points to p
, won't the assigned p=p->next
be removed anyhow in delete temp
, making this function fail? Is there something I'm missing? Perhaps something to do with that the pointer p
is passed as a reference?
Thank you.
Since temp points to
p
, won't the assignedp=p->next
be removed anyhow in delete temp, making this function fail?
temp
doesn't point to p
but to what p
points. Note that the pointers are vars having addressees as values and when a pointer on the rhs it returns its value.
And the assignment p = p -> next
makes the value of p
be the address of the of the node after p
(i.e) the address returned by p -> next