Thursday, 26 September 2013

is this linkedlist code a good practice?

is this linkedlist code a good practice?

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.

No comments:

Post a Comment