取消列表中某个值以下的元素 [英] Cancelling elements of a list under a certain value

查看:44
本文介绍了取消列表中某个值以下的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从列表中删除值较小的元素.

I need to delete elements minor of a value from a list.

我正在使用此功能取消键为<的节点.平均数.问题在于,当删除后打印列表时,由于指针似乎不为NULL,所以会出现无限循环,但是要退出该函数,它必须为NULL.

I am using this function for cancelling nodes with key < average. The problem is that when i print the list after deleting, i get an infinite loop because the pointer doesnt seem to become NULL, but for exiting the function, it has to be NULL.

void Cancel_Node(struct node *head , int average){
    struct node *temp;
    temp = head;
    struct node *prox = temp->next;
    while(temp !=NULL && prox != NULL){
       if(temp->key <= average){
            prox = temp->next;
            free(temp);
            temp = prox;
        }
        else{
            prox=temp->next;
            temp= temp->next;   
        }   
    }
}

多数民众赞成在结构,这是一个经典的链表:

Thats the struct, it's a classic linked list:

struct node{
    int key;
    struct node *next;
};

它工作正常,如果我在取消之前打印,我得到所有列表而没有错误,那么如果我调用cancel然后我尝试打印,我将得到一个无限循环,因为head!= NULL从未实现,但是我没有明白为什么.这可能是一个简单的问题,但我卡住了

It works fine, if i print before cancelling, i get all the list without errors, then if i call cancel and then i try to print, i get an infinite loop because head!= NULL is never fulfilled, but i dont get why. It is probably an easy problem but im stucked

推荐答案

嘿,这是使用双指针的好时机.我们通过保留指向下一个指针的指针,而不是像这样指向节点的指针来释放节点:

Hey this is a great time to use double pointers. We free nodes by keeping a pointer to the next pointer rather than a pointer to the node like so:

void Cancel_Node(struct node **head , int average){
    while(*head){
       if(head[0]->key <= average){
            struct node *temp = *head;
            *head = temp->next;
            free(temp);
        }
        else{
            head = &head[0]->next;
        }   
    }
}

您的算法会浪费自己的时间,因为边缘情况没有得到正确处理,可能会导致您注意到无限循环行为.解决该问题的最简单方法是删除边缘情况.双指针解决方案没有任何边缘情况.

Your algorithm can trash itself because the edge cases aren't handled correctly, probably causing the infinite loop behavior you noticed. The easiest way to deal with the problem is to remove the edge cases; the double pointer solution doesn't have any edge cases.

这篇关于取消列表中某个值以下的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆