Linked List does head node need to be allocated for?

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!
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top