Is p-> next-> prev the same as p?

I am implementing a Linked List implementation for my Uni, and I came across this code in 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 p->next->prev = p->prev; part is the same as saying p = p->prev; , because the previous of the next p is p itself.

Thanks in advance for any answers.

EDIT 1: A typo has been fixed and a bit more code has been added to make this more understandable.

+5
source share
2 answers

I was wondering if p->next->prev = p->prev; part is the same as saying p = p->prev

No, it is not. It sets the prev field to the next node, which follows the p node in the list.

The code removes the p node from the list. The two surrounding nodes on either side of the p node must be updated to stop pointing to the p node and instead point to each other. You showed only half the required 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 to the head of the list node, and if so, then update the head to p->next instead. Similarly, with the tail of the list node, if any, specify in p->prev .

In addition, if(p=NULL) in the code is incorrect, it must be if(p==NULL) . And if(p->next==NULL) in your code is also incorrect, it should be if(p->next!=NULL) .

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 finally, you should consider using the STL std::list container instead of a manual implementation.

+7
source

Not really. p is a local variable. p->next->prev is an instance variable on p->next . A change in the former will not affect the structure at all, but a change in the latter will. In other words, their values may be the same, but the memory addresses where these values ​​are stored are different.

+8
source

All Articles