dimanche 1 mars 2015

Adding node to singly linked list not working properly



I have a singly linked list struct and a local Node declared in main with my addToList function, but every time addToList executes it runs the case (head == NULL). Even when I already added values to the list. I am sure there is a small bug in my code, I just can't find it.



typedef struct node{
char* name;
int groupSize;
int status;
struct node* next;
}Node;

void addToList(char* name, Node* head, int groupSize, int status){

if(head == NULL){
head =(Node*)malloc(sizeof(Node));
head->name = (char*) malloc(sizeof(char)*30);
strcpy(head->name, name);
head->groupSize = groupSize;
head->status = status;
head->next = NULL;
printf("Name is %s\n\n", head->name);
}

else {
printf("entered else\n");
Node *tmp = head;
if(tmp->next!=NULL){
tmp = tmp->next;
}
tmp->next = (Node*) malloc(sizeof(Node));
tmp->next->name = (char*) malloc(sizeof(char)*30);
strcpy(tmp->next->name, name);
tmp->next->groupSize = groupSize;
tmp->next->status = status;
tmp->next->next = NULL;
}

int main(){
Node* head = NULL;

//TESTNG SECTION

addToList("Julio", head, 5, 7);

addToList("Francisco", head, 5, 7);

addToList("Jorge", head, 5, 7);

}



Aucun commentaire:

Enregistrer un commentaire