删除单链表指定结点出现段错误?

起初我是这么写的:

struct node * deletenode(struct node *head,int b){
    struct node *pre,*cur;
    pre=NULL;
    cur=head;
    if(head&&head->data==b){
        head=head->next;
        free(cur);
    }    
    else{
        while(cur->data!=b){
            pre=cur;
            cur=cur->next;
        }
        pre->next=cur->next;
        free(cur);    
    }
    return head;
}

结果提交时说段错误,改成下面这样就通过了,暂时还不知道为啥。。。

struct node * deletenode(struct node *head,int b){
    struct node *pre,*cur;
    pre=NULL;
    cur=head;
    if(head&&head->data==b){
        head=head->next;
        free(cur);
    }    
    else{
        while(cur){
        if(cur->data==b){
            pre->next=cur->next;
            free(cur);
        } 
        pre=cur;
        cur=cur->next;
    }
    return head;
    }
}

 

 

posted @ 2019-09-15 16:27  小泰格儿  阅读(432)  评论(0编辑  收藏  举报