I've written a function for adding to the end of a singly linked list in C. But what I don't get is why if the head element is NULL, why it continues remaining to be NULL after successive adds.
The struct is defined as this:
typedef struct node* node;
struct node {
int data;
node next;
}
In the main I have this:
node test = NULL;
add(test,1);
add(test,2);
add(test,3);
function add is defined as such:
void add(node head, int newData) {
node n = createNode(newData);
if (head==NULL) {
head = n;
return;
}
else {
node tmp = head;
while (tmp->next != NULL) {
tmp = tmp->next;
}
tmp = n;
}
}
createNode is defined as thus:
node createNode(int data) {
node n = (node) malloc(sizeof(struct node));
n->next = NULL;
n->data = data;
return n;
}
What I am confused about is that, the add function works fine if I first initialize the head (node test = createNode(1)) and then proceeds to add the rest of the values alright. But if I leave the test node to be NULL, it doesn't add any values? What is happening here?
node*to your functionadd, it will work. Also, u need to change the code in ur function accordingly .typedefpointers, but the struct. This will create less confusion.