Reputation: 125
Hi everyone I am a newbie in C and trying to learn it. I have a simple query regarding this linkedlist implementation which I found at many places:
void addNode(node **listhead, int data, int pos){
if(pos<=0 || pos > length(*listhead)+1){
printf("Invalid position provided, there are currently %d nodes in the list \n", length(*listhead));
return;
}else{
node *current = *listhead;
node *newNode = (node*)malloc(sizeof(node));
if(newNode == NULL){
printf("Memory allocation error\n");
return;
}
newNode->data = data;
newNode->next = NULL;
if (current == NULL){
*listhead = newNode;
return;
}else{
int i = 0;
while(current->next != NULL && i < pos-1){
++i;
current = current->next;
}
if(current->next == NULL){
current->next = newNode;
}
if(i == pos-1){
newNode->next = current->next;
current->next = newNode;
}
}
}
}
int main(){
node *head = NULL;
node **headref = &head;
addNode(headref, 1, 1);
addNode(headref, 2, 2);
addNode(headref, 3, 3);
printList(head);
return 0;
}
my query is here we are creating a pointer to a pointer which is pointing to NULL. This code works, however I wanted to know if this is a good practice. If it is not, how should I create my head pointer and pass its reference to the addNode function.
Upvotes: 0
Views: 474
Reputation: 1445
For single linked list, it is actually a good practice, which simplifies the addNode implementation.
I guess the call to addNode(node_x, 1, 1)
will add a node before node_x
. If you pass only the pointer to node_x
. Then the function will need to loop over the entire list and find the node before node_x
and modify its pointer to the new constructed node. While if you pass a pointer to pointer, let's say node** p
then the function only needs to assign the address of the new node to *p
.
Upvotes: 0
Reputation: 4666
We pass a double pointer to addNode() for cases, where the headref pointer needs to be updated. For such cases, with "addNode(headref, 1, 1);", the addNode would most likely be storing the address of the malloced element inside addNode() in the headref. If you were to pass headref as a pointer, then after the call headref would continue to point to the address in the main and you would lose the malloced address.
Upvotes: 0
Reputation: 121759
Suggested alternative:
int main() {
node *head = addNode(NULL, 1, 1);
node *current = head;
current = addNode(current, 2, 2);
current = addNode(current, 3, 3);
printList(head);
return 0;
}
In other words:
1) addNode() becomes a function that takes the current value as a parameter (so it doesn't have to traverse the entire list just to add a new element)...
2) ... and it returns a pointer to the new node.
3) This means at ANY point in the program you can access ANY of a) the list head, b) the previous pointer (before "add") and/or c) the next pointer (after add).
Upvotes: 2