I am doing a Linked List implementation for my Uni, and i came across this code on our presentations.
template <class X> bool linkedList<X>::deleteElement(node<X> *p)
if (p=NULL)
return false;
if(p->next!=NULL)
p->next->prev = p->prev;
if(p->prev!=NULL)
p->prev->next = p->next;
else
head = p->next
I was wondering if the p->next->prev = p->prev;
part is the same as saying p = p->prev;
because the previous of the next of p, is p itself.
Thanks in advance for any answers.
EDIT 1: Fixed a typo and added a bit more code to make this more clear.
temp will point to the current node(will have the address of the current node) whereas temp->next will point to the next node after the current node.
The -> symbol is an operator to select an element from a data structure pointed to by a pointer. So suppose you have a pointer defined as mystruct *p and it points to a mystruct instantiation.
prev is the previous element to x.
node *&temp represents a reference to a pointer to a node struct. If you change the value of temp , you modify the original pointer passed by reference.
Not quite. p
is a local variable. p->next->prev
is an instance variable on p->next
. Changing the former won't affect the structure at all, while changing the latter will. To put it another way, their values may be the same, but the memory addresses where those values are stored are different.
I was wondering if the
p->next->prev = p->prev;
part is the same as sayingp = p->prev
No, it is not. It is setting the prev
field of the next
node that follows the p
node in the list.
The code is removing the p
node from the list. The two surrounding nodes on either side of the p
node need to be updated to stop pointing at the p
node and instead point at each other. What you showed is only half of the necessary update. You need to add the other half: if (p->prev != NULL) p->prev->next = p->next;
. You also need to check if p
points at the head node of the list, and if so then update the head to point at p->next
instead. Likewise with the list's tail node, if any, to point at p->prev
.
Also, the if(p=NULL)
in your code is wrong, it should be if(p==NULL)
instead. And the if(p->next==NULL)
in your code is also wrong, it should be if(p->next!=NULL)
instead.
Here is the correct implementation:
template <class X> bool linkedList<X>::deleteElement(node<X> *p)
{
if (p == NULL)
return false;
if (p->next != NULL)
p->next->prev = p->prev;
if (p->prev != NULL)
p->prev->next = p->next;
if (p == head)
head = p->next;
// if your list has a tail:
if (p == tail)
tail = p->prev;
// if your list owns the memory for the nodes:
delete p; // or however you free it
return true;
}
And lastly, you should consider using the STL std::list
container instead of a manual implementation.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With