I was studying about Linked Lists from the book, "Introduction to Algorithms" by T Cormen.
There was an portion in the book as follows:
Given an element x in the list, x.next points to its successor in the linked list, and x.prev points to its predecessor.
If x.prev=NIL, the element x has no predecessor and is therefore the first element, or head, of the list. If x.next=NIL, the element x has no successor and is therefore the last element, or tail, of the list. An attribute L.head points to the first element of the list. If L.head=NIL, the list is empty.
The procedure LIST-DELETE removes an element x from a linked list L. It must be given a pointer to x, and it then “splices” x out of the list by updating pointers.
LIST-DELETE(L,x)
1 if x.prev!= NIL
2 x.prev.next = x.next
3 else L.head = x.next
4 if x.next !=
NIL
5 x.next.prev = x.prev
However, I did not get any of the portions in the text. First of all, they check whether the next possible memory address contained in x is NIL or not. If it is not NIL, then they replace x.prev.next by x.next. Now, x.prev.next is just a function that returns the memory address of x.key i.e returns the address in x. This means x.prev.next and x are the same. Finally, the statement x.prev.next=x.next seems nonsensical and absurd because x.prev.next is not a variable but a function that returns a value and assigning a new value to a "function return statement" makes no sense. So, I think, they tried to imply x=x.next and thus, the memory address in x becomes equal to the memory address of the next element after x.key.
Next, they check if, x.prev is equal to NIL this means, that x=L.head. Under this scenario, we change L.head to x.next i.e make the list start from the element after x.key. So, the element in memory address contained in x gets deleted.
Finally, it seems they check if x.next equal to NIL. If it is not, then, x.next.prev(=x)=x.prev.
Thus, the memory address stored in x gets replaced by the memory address returned by x.prev.
But I don't really have a clue how the real job of deletion of the element in the address contained in x, gets done. I have no idea about this.
i don't know about that book, but the problem with deleting elements inside a liked list is that you may destroy the link between the elements (because if you delete x then x.prev can't reach x.next and the list is now technically seperated into two lists).
to solve this problem we need to attach x.prev to x.next so x.prev.next is equal to x.next so we can delete x safely.
if you have a head or a tail in your linked list that points to the start and end of the list then you should be aware when deleting these elements.
if you are deleting the first element (lets say x) then you need to make head equal to x.next
but if you are deleting the last element then tail should be equal to x.prev.