trying to create a insert method thats takes a char *name and int age. after than iam trying to insert in linked list. its seem to be working fine but if i have a linked lets say [1 2 3 4 5] and if i try to insert(2). i shoudl get result of [1 2 2 3 4 5] but it dont work. not sure why.
void insert(char *na, int ag)
{
struct node *cur_node = head;
struct node *new_node;
int skip = 0;
int in_list = 0;
if(cur_node == NULL)
{
head = (struct node *) malloc(sizeof(struct node));
if(head == NULL)
{
printf("Node allocation failed.\n"); fflush(stdout);
exit(1);
}
strcpy(head->name, na);
head->age = ag;
head->next = NULL;
}
else
{
/* skip double */
while(cur_node != NULL)
{
if(strcmp(cur_node->name, na) == 0)
{
skip = 1;
}
cur_node = cur_node->next;
}
if(skip == 0)
{
/* insert at begining */
cur_node = head;
if(head->age >= ag)
{
new_node = (struct node *) malloc(sizeof(struct node));
if(new_node == NULL)
{
printf("Node allocation failed.\n"); fflush(stdout);
}
strcpy(new_node->name, na);
new_node->age = ag;
new_node->next = head;
head = new_node;
in_list = 1;
}
/******************* 1 2 3 4 insert(2) ------------------ doesnt work **************/
/* insert in middle */
cur_node = head;
while(cur_node != NULL && cur_node->next != NULL)
{
if(cur_node->age < ag && cur_node->next->age > ag)
{
new_node = (struct node *) malloc(sizeof(struct node));
if(new_node == NULL)
{
printf("Node allocation failed.\n"); fflush(stdout);
}
strcpy(new_node->name, na);
new_node->age = ag;
new_node->next = cur_node->next;
cur_node->next = new_node;
in_list = 1;
}
cur_node = cur_node->next;
}
/* insert at end */
if(in_list == 0)
{
cur_node = head;
while(cur_node->next != NULL)
{
cur_node = cur_node->next;
}
new_node = (struct node *) malloc(sizeof(struct node));
if(new_node == NULL)
{
printf("Node allocation failed.\n"); fflush(stdout);
exit(1);
}
strcpy(new_node->name,na);
new_node->age = ag;
new_node->next = NULL;
cur_node->next = new_node;
}
}
}
}//end of insert method