为了账号安全,请及时绑定邮箱和手机立即绑定

关于双链表删除任意数据!

关于双链表删除任意数据!

asdhjhg 2017-05-29 16:40:39
今天归纳链表的时候,写了一个删除double linklist的任意数据,我觉得自己写的好臃肿,虽然g++过了,但是总觉得是不是哪里欠妥当。。。。。强迫症,总是感觉代码是不是不够精炼。。。。请大神给我提意见。。。自己有python和linux的一点点基础。。。C才学一个月,轻喷。。。一下是delete部分的代码!struct Node *delete_givendata(int data) {     struct Node *current = head;     struct Node *temp = NULL;     struct Node *temp1 = NULL;     if (head == NULL) return NULL;//empty!     while (current -> data != data)//find the data we want to delete.     {         current = current -> next;     }     if (current == head && current -> next != NULL)//the first data is that data we want to delete     {         head = current -> next;         current -> next -> prev = NULL;         free(current);         return head;     }     else if (current -> prev != NULL && current -> next == NULL)//the last data is that data we want to delete     {         current -> prev -> next = NULL;         free(current);         return head;     }     else if (head -> next == NULL)//just one data in list     {         head = NULL;         free(current);         return head;     }     //the data in (first+1,last-1)     temp = current -> prev;     temp1 = current -> next;     temp -> next = temp1;     temp1 -> prev =  temp;     free(current);     return head; }
查看完整描述

2 回答

?
onemoo

TA贡献883条经验 获得超454个赞

你这个代码第 7 行 while 语句处好像有逻辑问题吧?  你说代码通过了,我不知道你有没有进行充分地测试。

这个 while 是为了找到等于 data 值的 node,可你没考虑找不到的情形。

假设这个链表中只有一个首 node,而且它的值还不是 data。那么 while 第一次循环后 current 就已经是 NULL 了,第二次进入 while 循环时就会因为访问 NULL 指针而出错退出。

查看完整回答
反对 回复 2017-06-09
?
为梦想努力_冬

TA贡献56条经验 获得超14个赞

666,厉害了

查看完整回答
反对 回复 2017-05-30
  • asdhjhg
    asdhjhg
    就这还666,其实我觉得真的写的挺臃肿的,给点意见啊
  • 2 回答
  • 0 关注
  • 1680 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信