Pointer again

I am trying to create link list for my project. Basic thing is to set the header to NULL right. I don understand why all the tutorial i read through require me to set the struct node pointer to NULL instead of the head -> next pointer to null. Cos i though we are using the next ptr to point to next node instead of the struct .


typedef struct node
{
int data; // will store information
node *next; // the reference to the next node
};


node *head = NULL; //empty linked list

================================== Below is my code===========================

struct studentNode
{
studentNode *next;
int average;
char studentID[10];

};

int main()
{

studentNode a;
studentNode *head = &a;

initailizeList(head);

system("pause");
}

void initailizeList(studentNode *head)
{


if(head -> next != NULL)
{

head -> next = NULL;
}


}

May i know what is the different between my code and the above tutorial code

Last edited on
head is the first link in the linked list. Initially, when the list is empty, it must be NULL to indicate there isn't a node. As to what value your next pointer takes, depends on whether you're inserting at the beginning or end of the list.

On adding an entry to the list, you create a new node that will go on the end of the list. So you set it's next pointer to NULL to show that. Then you walk to the end of the list and change the old end to point to the newly created node. So in this instance, you need next to be NULL.

The other way is if you insert your new entry at the beginning of the list, then the new node's next pointer will intially be the same as head. You then change head to point to your node. So in this instance, next is initialised with the value of head.
Topic archived. No new replies allowed.