如果(条件)从链表中删除一个节点

Remove a node from linked list if (condition)

我的链表是从具有 4 个整数的结构构建的。 只要整数 ttl 低于 1,就应该从我的列表中删除该节点。 我目前拥有的代码在某些情况下有效,即仅当要删除的节点位于列表的头部时。

typedef struct _ttl_t {
    int x;
    int y;
    int value;
    int ttl;
    struct ttl *next;
} ttl_t;



ttl_t *remove_ttl (ttl_t *head) { // ’r’ command
    if (head==NULL){
        return head;
    }
    else {
        ttl_t *curr=head;
        while (curr){
            if (curr->ttl<1){
                head=curr->next;
                free(curr);
            }
            curr=curr->next;
        } 
    }
    return head;
}

对于初学者来说,typedef

中的结构声明
typedef struct _ttl_t {
    int x;
    int y;
    int value;
    int ttl;
    struct ttl *next;
} ttl_t;

不正确。 struct _ttl_tstruct ttl 是两种不同的类型。我想你的意思是

typedef struct _ttl_t {
    int x;
    int y;
    int value;
    int ttl;
    struct _ttl_t *next;
} ttl_t;

这个循环

    while (curr){
        if (curr->ttl<1){
            head=curr->next;
            free(curr);
        }
        curr=curr->next;
    } 

也是不正确的,因为如果节点的数据成员 ttl 小于 1,则头节点会更改,尽管它自己的数据成员 ttl 可以大于或等于 1。

通过指针引用传递头节点,函数定义更简单

例如

void remove_ttl( ttl_t **head ) 
{
    while ( *head != NULL )
    {
        if ( ( *head )->ttl < 1 )
        {
            ttl_t *tmp = *head;
            *head = ( *head )->next;
            free( tmp );
        }
        else
        {
            head = &( *head )->next;
        }
    }
}