c - 删除c中链表中的元素

标签 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");
    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");
    }
}

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

最佳答案

你的意思似乎是这样的

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;
}

请考虑该功能不应发出消息。由函数的客户端决定是否发出消息。

这是一个演示程序。

#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;
}

它的输出是

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 

关于c - 删除c中链表中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49406098/

相关文章:

c# - 按索引向自定义链表添加节点,向右移动

c - 如何在不违反 MISRA 规则的情况下将位域变量分配给 uint8_t 变量?

list - 计算列表中原子的所有出现次数? - 口齿不清

python - python中所有可能的列表合并

java - java中如何链接两个链表的元素?

c++ - 相同的代码在在线 IDE 和本地 IDE 中给出不同的结果

c - 如何使用 switch case 更新值

收集值并将其存储在单独的变量中

c++ - C/C++ : is it possible to pass binary data through the console?

C++ 设计 : Template Function for Random Deletion by Index for list & vector