Created
July 19, 2020 03:08
-
-
Save shiywang/bfb708655f6fa8004a16ccca5eae9659 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
#include <stdbool.h> | |
typedef struct node | |
{ | |
struct node * next; | |
int val; | |
} node; | |
bool remove_is_5(node const *v) { | |
return v->val == 5; | |
} | |
typedef bool (*remove_fn)(node const*v); | |
node *head = NULL; | |
node *tail = NULL; | |
int size = 0; | |
void Head(int val) { | |
node *add = malloc(sizeof(node)); | |
add->val = val; | |
add->next = head; | |
head = add; | |
if(size == 0) tail = head; | |
size++; | |
} | |
void Tail(int val) { | |
node *add = malloc(sizeof(node)); | |
add->val = val; | |
tail->next = add; | |
tail = add; | |
if(size == 0) head = tail; | |
size++; | |
} | |
void DumpLinkedList(node * ref) { | |
printf("-----------------\n"); | |
node *it = ref; | |
for(int i = 0; i < size; i++) { | |
printf("%x %d\n", it, it->val); | |
it = it->next; | |
} | |
printf("-----------------\n"); | |
} | |
void remove_if(node ** head, remove_fn rm) | |
{ | |
for (node** curr = head; *curr; ) | |
{ | |
node * entry = *curr; | |
if (rm(entry)) | |
{ | |
*curr = entry->next; | |
size--; | |
free(entry); | |
} | |
else | |
curr = &entry->next; | |
} | |
} | |
int main() { | |
Head(3); | |
Head(4); | |
Head(5); | |
Tail(6); | |
Tail(6); | |
Tail(6); | |
DumpLinkedList(head); | |
remove_if(&head, remove_is_5); | |
DumpLinkedList(head); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment