在c中删除链表中的元素

在c中删除链表中的元素,c,list,linked-list,singly-linked-list,C,List,Linked List,Singly Linked List,C中的这个过程应该根据链表的数据删除链表中的一个元素,但每次我调用它时,它都会被卡住。我可以确认问题不在于声明列表的类型或其他相关内容 void supprime(list *head, int data2) {//failed //data2 refers to the value we are looking for list p= *head, k; if (*head== NULL) printf("the list is empty"); el

C中的这个过程应该根据链表的数据删除链表中的一个元素,但每次我调用它时,它都会被卡住。我可以确认问题不在于声明列表的类型或其他相关内容

void supprime(list *head, int data2) {//failed
//data2 refers to the value we are looking for
    list p= *head, k;
    if (*head== NULL) 
        printf("the list is empty");
    else {
        while ((p->data!= data2) && (!p)) {
            k= p;
            p= p->next;
        }
        if (p->data == data2) {
            k->next= p->next;
            free(p);
        }
        else 
            printf("This data is not available\n");
    }
}

如果有人想要,只是为了确保一切正常。

你的意思似乎是如下所示

int supprime( list *head, int data ) 
{
    while ( *head && ( *head )->data != data ) head = &( *head )->next;

    int success = *head != NULL;

    if ( success )
    {
        list tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }

    return success;
}
考虑到finction不应发出消息。由函数的客户端决定是否发出消息

这是一个演示程序

#include <stdio.h>
#include <stdlib.h>

typedef struct cell 
{
    int data;
    struct cell *next;
} cellule;

typedef cellule *list;

void affiche_liste( list head ) 
{
    for ( ; head; head = head->next )
    {
        printf( "%d ", head->data );
    }
}

int ajout_fin( list *head, int data ) 
{
    list tmp = malloc( sizeof( *tmp ) );
    int success = tmp != NULL;

    if ( success )
    {
        tmp->data = data;
        tmp->next = NULL;

        while ( *head ) head = &( *head )->next;

        *head = tmp;
    }

    return success; 
}

int supprime( list *head, int data ) 
{
    while ( *head && ( *head )->data != data ) head = &( *head )->next;

    int success = *head != NULL;

    if ( success )
    {
        list tmp = *head;
        *head = ( *head )->next;
        free( tmp );
    }

    return success;
}

int main(void) 
{
    const int N = 10;
    list head = NULL;

    int i = 0;
    for ( ; i < N; i++ )
    {
        ajout_fin( &head, i );
        affiche_liste( head );
        putchar( '\n' );
    }

    while ( i )
    {
        supprime( &head, --i );
        affiche_liste( head );
        putchar( '\n' );
    }

    return 0;
}

请出示证件。特别是,您需要展示如何在((p->data!=data2)和(&&(!p))时调用
supprime
{
您应该反转这些。还有许多其他可能出现的问题,例如,如果删除第一个节点,则取消引用
k
未初始化。@Johnnymop是的,如果p为
NULL
,我们需要先检查,然后再访问
p->data
@ryker低资格程序员发明名称,如data3,然后发明原因参数可以像数据一样命名。
0 
0 1 
0 1 2 
0 1 2 3 
0 1 2 3 4 
0 1 2 3 4 5 
0 1 2 3 4 5 6 
0 1 2 3 4 5 6 7 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 8 9 
0 1 2 3 4 5 6 7 8 
0 1 2 3 4 5 6 7 
0 1 2 3 4 5 6 
0 1 2 3 4 5 
0 1 2 3 4 
0 1 2 3 
0 1 2 
0 1 
0