您的位置:首页 > 其它

删除链表节点的二种方法比较

2013-01-12 10:46 211 查看
可以比较下二种方法实现的差异,你更喜欢哪种呢?

方法一:

typedef struct node  

{  

    struct node * next;  

    ....  

} node;  

 

typedef bool (* remove_fn)(node const * v);  

 

// Remove all nodes from the supplied list for which the   

// supplied remove function returns true.  

// Returns the new head of the list.  

node * remove_if(node * head, remove_fn rm)  

{  

    for (node * prev = NULL, * curr = head; curr != NULL; )  

    {  

        node * next = curr->next;  

        if (rm(curr))  

        {  

            if (prev)  

                prev->next = curr->next;  

            else  

                head = curr->next;  

            free(curr);  

        }  

        else  

            prev = curr;  

        curr = next;  

    }  

    return head;  



方法二:

void remove_if(node ** head, remove_fn rm)  

{  

    for (node** curr = head; *curr; )  

    {  

        node * entry = *curr;  

        if (rm(entry))  

        {  

            *curr = entry->next;  

            free(entry);  

        }  

        else  

            curr = &entry->next;  

    }  

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C LIST