I’m having a hard time coming up with the logic for removing some node from both a doubly and singly linked list. I’ve looked online from help, but I couldn’t find a simple example of it. Here is what I have:
Doubly linked deletion. dCurrent is the node that we want to delete.
if (dCurrent == dHead){
dHead = dCurrent->next;
dHead->prev = NULL;
}
else if(dCurrent == dTail){
dTail = dCurrent->prev;
dTail->next = NULL;
}
else{
dCurrent->next->prev = dCurrent->prev;
dCurrent->prev->next = dCurrent->next;
}
Here is what I have for the singly linked list. Again, sCurrent is the node to delete. and sPrev = sCurrent->prev.
if(sPrev == NULL){
sHead = sCurrent->next;
}
else{
sPrev->next = sCurrent->next;
}
The problem is that after I delete a collection of random nodes from both lists, the doubly linked list displays correctly from head to tail, but not tail to head. The singly linked list doesn’t display correctly, either.
Your doubly-linked-list logic looks fine to me. My only concern is that if
dCurrentis the only element in the list, then this:will most likely try to reference a null-pointer. (It depends on how you design your list. But in a typical design, if
dCurrentis the only node, thendCurrent->nextisNULL.)Your singly-linked-list logic also looks fine to me, in the abstract, given the assumption that “sPrev = sCurrent->prev”; but I don’t understand how that assumption can be correct. If it’s a singly-linked list, then
sCurrentdoesn’t have aprevpointer.