【问题标题】:deleting an element in a linked list in c在c中删除链表中的元素
【发布时间】:2018-08-30 13:25:08
【问题描述】:

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,只是为了确保一切正常。

【问题讨论】:

  • 请显示minimal reproducible example。特别是你需要展示你如何调用supprime。
  • while ((p->data!= data2) && (!p)) { 你应该把它们颠倒过来。
  • 还有很多其他可能的问题,比如在删除第一个节点时取消引用k uninitialized。
  • @JohnnyMopp 是的,如果 p 是 NULL,我们需要先检查一下,然后再访问 p->data
  • @ryyker 低素质的程序员发明了像 data3 这样的名字,然后发明了使用它们的理由。参数可以像数据一样命名。

标签: c list linked-list singly-linked-list


【解决方案1】:

你的意思好像是这样的

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 

【讨论】:

    猜你喜欢
    • 2020-09-04
    • 2021-03-26
    • 1970-01-01
    • 2020-02-14
    • 1970-01-01
    • 2014-10-25
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多