先创建结构体 struct student { int data; //int tag;//标记这是第几个 struct student *next; }; // addone 用于将一个数插入已从小到大排好序的链中 struct student *addone(struct student *h,int x){ if(h==NULL) //?????? printf("this is NULL"); int tag=0;//假设还没添加进入链 struct student *p=h,*temp=NULL,*temp1=NULL; temp1=(struct student * )malloc(sizeof(struct student));//创建内存 temp1->data=x; printf("%d",temp1->data); if(h==NULL){//若链为空 h=temp1; h->next=NULL; p=h->next; } while(p!=NULL){ if(p->data>x){ temp1->next=p; if(temp==NULL){ //若第一个元素就满足条件的话 h=temp1; tag=1;//已经插入 break; } else{ //若不是第一个满足条件 // printf("0"); temp->next=temp1; //printf("a"); tag=1; //printf("b"); break; } } temp=p;//本轮该数不满足条件将它的地址存起来方便下一个满足条件的数进行连接 printf("r "); p=p->next; } if(!tag){//若循环完都没满足条件的说明只能插在最后 temp1->next=NULL; temp->next=temp1; tag=0; } return h;//插入完成返回指针 } //删除传入的与x所有相同的数 struct student *deleteEle(struct student *h,int x){ struct student *p=h,*temp=NULL,*temp1=NULL; //init if(h==NULL){ /*若链表为空*/ printf("null"); return 0; } while(p!=NULL){ //当该元素不为空时 if(p->data==x){ if(temp==NULL){ //if it's the same and it's the first one;free it and set head; printf("%d\n",h); h=p->next; free(p); p=h; //and 更新指针p让它指向head 这样可以继续执行delete printf("%d\n",h); } else{ //not the first one(include the last one!if the last one jump out! else continue!) temp->next=p->next; free(p); p=temp->next; } //temp1=p; continue; //the p is right;don't need to go } temp=p;//if it's not the the same;continue the next one; p=p->next; } return h;//返回头指针 }