I have a linked list, and I need to create a node right after the head..
it means I have something like this:
node *head = NULL;
and my linked list in the end should be like :
head -> node -> NULL…
but when I use a normal addNode function, it gives me a runtime error(not sure which, my debug has problems)…
this is what I wrote:
void addNode(node *head)
{
node *temp = head; // a temp to not move the head
node *newNode = (node*)malloc(sizeof(node)); // The new node
while (temp -> next != NULL)
{
temp = temp -> next // Getting to the last node
}
temp -> next= newNode; // Adding the new node into the linked list insted of the NULL
newNode -> next = NULL; // Adding the NULL after the new node
}
This code works great to me when I have a linked list with already 1 or more nodes ,but if the linked list only has a head, it does problems to me… how can I solve the problem?
(if you didnt understand my problem – With the addNode function I wrote here, i’m getting a runtime error for adding a new node into a head that points to NULL already)..
Thanks, Amit 🙂
You have to check if Head is null. Otherwise when you try to check
head is NULL so you are referring to random place in memory
You can’t add node after head if head is NULL. You have to allocate memory for head and then set ‘next’ pointer. By the way why u want to set head->next while head is null?
EDIT
Mayby you should try add flag to nodes like bool active and set it false when you want to pass it.
I’ll try to say it in another way. You can’t set head->next because head is NULL. NULL means, that it’s just a pointer, to nowhere. It’s a variable where u can place some address, but nothing else. If u want to have there a structure, like node, you have to place there address of new object of type Node:
After that u will have in head address of Node object and u will be able to revoke to variables (like Node *next) inside this structure.