Think是一种按名称顺序插入新元素的函数。 我知道如何做到这一点,如果我使用if来分开开始和其他插入条件。但我被要求将if和while合并成一个while循环。 我怎样才能将插入函数集成到一个while循环与指针指针?如何使用指向要插入链接列表的指针的指针
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;
}
}
在至少你必须使'people'参数成为指针的指针。否则,你只需要通过指向指针的指针来改变局部变量,但是你必须能够从调用函数中更新头指针。链接列表在这里是一个流行的话题,看看相关的问题。 –
您的顶层'else'分支不返回任何内容。 –