算法 单链的创建与删除

编程技术  /  houtizong 发布于 3年前   123
先创建结构体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; //initif(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 这样可以继续执行deleteprintf("%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;//返回头指针}

请勿发布不友善或者负能量的内容。与人为善,比聪明更重要!

留言需要登陆哦

技术博客集 - 网站简介:
前后端技术:
后端基于Hyperf2.1框架开发,前端使用Bootstrap可视化布局系统生成

网站主要作用:
1.编程技术分享及讨论交流,内置聊天系统;
2.测试交流框架问题,比如:Hyperf、Laravel、TP、beego;
3.本站数据是基于大数据采集等爬虫技术为基础助力分享知识,如有侵权请发邮件到站长邮箱,站长会尽快处理;
4.站长邮箱:[email protected];

      订阅博客周刊 去订阅

文章归档

文章标签

友情链接

Auther ·HouTiZong
侯体宗的博客
© 2020 zongscan.com
版权所有ICP证 : 粤ICP备20027696号
PHP交流群 也可以扫右边的二维码
侯体宗的博客