A
Andrew
Does a linked list in C require that the head node allocate memory the
size of the structures in the node? Or can you just set the head node
structure equal to 0? I have tried creating lists both ways and they
seem to work the same. Are there any disadvantages or problems with
not allocating for the head node? I see in most text books that linked
lists are initialized as the following.
head = (struct node *) malloc(sizeof *head);
z = (struct node *) malloc(sizeof *z);
head->next = z; z->next = z;
But I seem to be successfull using just
head = 0;
with no z node and then whenever traversing the list returning NULL
when there is no match in the list. Such as the following.
struct node *GetNode(int v) {
if(head) {
struct node *tmpNode;
tmpNode = head;
while(tmpNode) {
if(tmpNode->key == v) return tmpNode;
tmpNode=tmpNode->next;
}
}
return NULL;
}
I know there must be a reason why this way is wrong but so far it
seemed to be working for me. Please let me know if there are any
reasons not to use this method and any advantages of the other way.
Thanks for any advice!
size of the structures in the node? Or can you just set the head node
structure equal to 0? I have tried creating lists both ways and they
seem to work the same. Are there any disadvantages or problems with
not allocating for the head node? I see in most text books that linked
lists are initialized as the following.
head = (struct node *) malloc(sizeof *head);
z = (struct node *) malloc(sizeof *z);
head->next = z; z->next = z;
But I seem to be successfull using just
head = 0;
with no z node and then whenever traversing the list returning NULL
when there is no match in the list. Such as the following.
struct node *GetNode(int v) {
if(head) {
struct node *tmpNode;
tmpNode = head;
while(tmpNode) {
if(tmpNode->key == v) return tmpNode;
tmpNode=tmpNode->next;
}
}
return NULL;
}
I know there must be a reason why this way is wrong but so far it
seemed to be working for me. Please let me know if there are any
reasons not to use this method and any advantages of the other way.
Thanks for any advice!