In a strict context to doubly linked lists in C, which is the right
way to insert an element?
For starters it seems you mean a singly-linked list instead of a doubly-linked list because neither provided code deals with a doubly-linked list.
You need to update the pointer head
that the first function performs because the pointer head
is passed to the function by reference (through a pointer to it) and dereferencing the parameter that accepts a pointer to the pointer head the function has a direct access to the pointer head.
As for this function
bool insertInFront( IntElement *head, int data ){
IntElement *newElem = malloc( sizeof(IntElement) );
if ( !newElem ) return false;
newElem->data = data;
newElem->next = head;
*head = *newElem; // <---------- check this line here!
return true;
}
then it does not do that, It tries to assign the node pointed to by the pointer head
with the dynamically allocated node pointed to by the pointer newElem
.
Pay attention to that the expression *head
yields an object of the type IntElement
that is a node instead of a pointer to a node.
As a result the function can invoke undefined behavior when head
is equal to NULL
due to dereferencing a null pointer. Moreover it has a memory leak because the dynamically allocated memory is not freed and its address will be lost after exiting the function. And it does not insert a new node. Instead it tries to change already existent node pointed to by the pointer head
.
As for a doubly-linked list then the function can look the following way provided that there is no one more declared structure that indeed defines a doubly-linked list by having pointers to the head and tail nodes.
bool insertInFront( IntElement **head, int data )
{
IntElement *newElem = malloc( sizeof( IntElement ) );
bool success = newElem != NULL;
if ( success )
{
newElem->data = data;
newElem->prev = NULL;
newElem->next = *head;
if ( *head ) ( *head )->prev = newElem;
*head = newElem;
}
return success;
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…