Search code examples
clinked-listpointer-to-pointer

how to use a pointer to pointer to insert in a linked list


Think is a function to insert new element in the order of name. I knew how to do it if I use a if to separate condition of inserting at the start and others. But I was asked to merge the if and while into a single while loop. How could i integrate the insert function into one while loop with pointer to pointer?

person* insert_sorted(person *people, char *name, int age)
{
    person *p=NULL;//,*t=NULL,*q=NULL;
    person *ptr= people;
    person **ptr2ptr=&ptr;

    p=malloc(sizeof(person));

    if ( p == NULL ){
        printf("malloc() failed\n");
        return NULL;
    }
    else {
        p->name = name;
        p->age = age;

        if ( people == NULL ){ // empty list
            people = p;
            people->next =NULL;
        }
        else{
            *ptr2ptr = ptr;
            while( (*ptr2ptr) !=NULL )
            {
                if ( compare_people(p, people)<=0 )  // insert at the start
                    break;
                else if ( (*ptr2ptr)->next == NULL) //insert at the end
                    break;
                else if ( compare_people(*ptr2ptr, p) <=0 && compare_people( p, (*ptr2ptr)->next)<=0 )//insert at the middle
                    break;
                *ptr2ptr = (*ptr2ptr)->next;
            }
            //insert at the end
            p->next =  (*ptr2ptr)->next;
            (*ptr2ptr)->next = p;

        }
    }

Solution

  • here i found the most useful answer to this question:http://www.mvps.org/user32/linkedlist.html

           ptr2ptr = &people;
            while ( *ptr2ptr!=NULL && compare_people(*ptr2ptr,p) ) {
                ptr2ptr = &(*ptr2ptr)->next;
            }
            p->next = *ptr2ptr;
            *ptr2ptr = p;