From de41cfb61d4cbafdc3ffe8a2651630a53b3c8d11 Mon Sep 17 00:00:00 2001 From: Tucker Evans Date: Fri, 24 Jul 2020 15:56:43 -0400 Subject: Add first/last getters for maps. --- collections/map/map.adoc | 49 ++++++++++++++++++++++++++++++++++++++++++++++++ collections/map/map.c | 24 ++++++++++++++++++++++++ collections/map/map.h | 3 +++ 3 files changed, 76 insertions(+) diff --git a/collections/map/map.adoc b/collections/map/map.adoc index 740df3c..690aa3d 100644 --- a/collections/map/map.adoc +++ b/collections/map/map.adoc @@ -119,6 +119,55 @@ assert(strcmp(tmp, "FOUR") == 0); free(tmp); ---- +[[map_first]] ++void* map_first(map *self)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Returns the value associated with the smallest key from +self+. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include + +char *str1 = "A"; +char *str2 = "Z"; + +map *dict = map_new((cmp_func) strcmp); + +map_insert(dict, str1, str1); +map_insert(dict, str2, str2); + + +assert(strcmp(str1, map_first(dict) == 0); +---- + +[[map_last]] ++void* map_last(map *self)+ +~~~~~~~~~~~~~~~~~~~~~~~~~~~~ +Returns the value associated with the largest key from +self+. + +Examples +^^^^^^^^ +[source,c] +---- +#include "map.h" +#include + +char *str1 = "A"; +char *str2 = "Z"; + +map *dict = map_new((cmp_func) strcmp); + +map_insert(dict, str1, str1); +map_insert(dict, str2, str2); + + +assert(strcmp(str2, map_last(dict) == 0); +---- + + [[map_swap]] +void map_swap(map *self, void *i, void *j)+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ diff --git a/collections/map/map.c b/collections/map/map.c index b0e095e..d581d81 100644 --- a/collections/map/map.c +++ b/collections/map/map.c @@ -497,6 +497,30 @@ void *key; return ret; } +void* map_first(root) +map *root; +{ + struct map_node *tmp; + + if (!root) + return; + + for (tmp = root->root; tmp->left; tmp = tmp->left); + return tmp->val; +} + +void* map_last(root) +map *root; +{ + struct map_node *tmp; + + if (!(root || root->root)) + return; + + for (tmp = root->root; tmp->right; tmp = tmp->right); + return tmp->val; +} + void map_swap(root, ikey, jkey) map *root; void *ikey, *jkey; diff --git a/collections/map/map.h b/collections/map/map.h index c6fb83d..b3ea4c5 100644 --- a/collections/map/map.h +++ b/collections/map/map.h @@ -14,6 +14,9 @@ int map_size(map*); int map_insert(map*, void*, void*); void* map_remove(map*, void*); +void* map_first(map*); +void* map_last(map*); + void* map_set_val(map*, void*, void*); void* map_index(map*, void*); -- cgit v1.1