linus建議的刪除單鏈表指定節點的方法
阿新 • • 發佈:2019-02-12
#include<stdio.h> #include<stdlib.h> struct node { int i; struct node* next; }; int rm_if(int i) { return i % 2; } void gen_list(struct node** head, int i) { if (i < 0) return; *head = (struct node*)malloc(sizeof(struct node)); (*head)->i = i; (*head)->next = NULL; gen_list(&((*head)->next), i - 1); } void del_odd(struct node** head, int(*fn)(int)) { struct node** tmp; for (tmp = head; *tmp; ) { struct node* entry = *tmp; if (fn(entry->i)) { *tmp = entry->next; free(entry); } else tmp = &entry->next; } } int main() { struct node** head, **tt; gen_list(head, 100); del_odd(head, rm_if); for (tt = head ; *tt;) { printf("%d ", (*tt)->i); tt = &((*tt)->next); } return 0; }