Reputation: 300
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?
Upvotes: 1
Views: 506
Reputation: 310930
Write function add
the following way
void add( node *head, int newData )
{
node n = createNode( newData );
while ( *head ) head = &( *head )->next;
*head = n;
}
or you can write even the following way
void add( node *head, int newData )
{
while ( *head ) head = &( *head )->next;
*head = createNode( newData );
}
and call it like
node test = NULL;
add( &test, 1 );
add( &test, 2 );
add( &test, 3 );
Take into account that function createNode
must be declared before function add
and you missed a semicolon in the structure definition
struct node {
int data;
node next;
}
^^^
Also it is not a good idea to use the same identifier for a struture tag and pointer to the same structure
typedef struct node* node;
At least it would be better to write something like
typedef struct node* node_ptr;
Upvotes: 2