This commit is contained in:
2022-02-17 18:21:04 +08:00
parent a64c19d111
commit 4bdef58fe5
2 changed files with 52 additions and 0 deletions

9
dict.h
View File

@@ -16,6 +16,15 @@ template <typename T, typename V>
size_t dict_count(struct Dict<T, V>* d) {
return linked_list_count((struct LinkedList<struct dict_entry<T, V>>*)d);
}
template <typename K, typename V>
bool dict_delete_internal(struct dict_entry<K, V> o, K key) {
return o.key == key;
}
template <typename K, typename V>
bool dict_delete(struct Dict<K, V>*& d, K key) {
if (!d) return false;
return linked_list_delete((struct LinkedList<struct dict_entry<K, V>>*&)d, key, dict_delete_internal);
}
template <typename T, typename V>
void dict_free(struct Dict<T, V>*& d, void(*free_func)(struct dict_entry<T, V>) = nullptr) {
return linked_list_clear((struct LinkedList<struct dict_entry<T, V>>*&)d, free_func);

View File

@@ -153,6 +153,49 @@ bool linked_list_delete(struct LinkedList<T>*& list, T data) {
return false;
}
template <typename T, typename D>
bool linked_list_delete(struct LinkedList<T>*& list, D data, bool(*is_same)(T, D)) {
if (!list || !is_same) return false;
struct LinkedList<T>* t = list;
while (t->prev) {
t = t->prev;
}
if (is_same(t->d, data)) {
if (t->prev) t->prev->next = t->next;
if (t->next) t->next->prev = t->prev;
if (t == list) {
if (t->prev) {
list = t->prev;
} else if (t->next) {
list = t->next;
} else {
list = nullptr;
}
}
free(t);
return true;
}
while (t->next) {
t = t->next;
if (is_same(t->d, data)) {
if (t->prev) t->prev->next = t->next;
if (t->next) t->next->prev = t->prev;
if (t == list) {
if (t->prev) {
list = t->prev;
} else if (t->next) {
list = t->next;
} else {
list = nullptr;
}
}
free(t);
return true;
}
}
return false;
}
template <typename T>
void linked_list_free_tail(struct LinkedList<T>*& list, void(*free_func)(T) = nullptr) {
if (!list) return;