Here is my code :
typedef struct node {
int data;
struct node *next;
} Node;
void add(Node *head, Node *node) {
Node *ptr;
ptr = head;
if(head==NULL) {
head=node;
}
else {
while(ptr->next != NULL) {
ptr = ptr->next;
}
ptr->next = node;
}
}
Node* create(int a) {
Node *node;
node = (Node*)malloc(sizeof(Node));
node->data = a;
node->next = NULL;
return node;
}
int main() {
Node *head;
head = NULL;
int i;
for(i=0; i<10; i++) {
Node *node;
node = create(i);
add(head, node);
}
}
Problem is : head is getting redefined in the function add, everytime add is called. why ?
Because
addis receiving a copy of your pointer when you call it. You setheadin that function, but that changes the local copy, not other variable namedheadinmain(). You would need to do something like this (I just put the lines to change; the rest look okay):