算法 单链的创建与删除


先创建结构体
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;//返回头指针
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值