summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--lichen.c7
-rw-r--r--lichen.h5
-rw-r--r--lichen.test.c24
3 files changed, 35 insertions, 1 deletions
diff --git a/lichen.c b/lichen.c
index d7f0f82..912dbff 100644
--- a/lichen.c
+++ b/lichen.c
@@ -133,3 +133,10 @@ int li_copy_list(struct li_ll_t **dst, struct li_ll_t *src, void *(*copy_data)(v
return 0;
}
+
+
+int li_sort_list(struct li_ll_t *list, int (*compare_data)(void *, void*)) {
+ list = list;
+ compare_data = compare_data;
+ return 0;
+}
diff --git a/lichen.h b/lichen.h
index 5f13e85..3a8cce9 100644
--- a/lichen.h
+++ b/lichen.h
@@ -49,10 +49,13 @@ typedef struct li_ll_t {
struct li_ll_t * li_alloc_ll();
// free a linked list
void li_free_ll(struct li_ll_t *list, void (*free_data)(void*));
+// prepend and append to a linked list
int li_ll_append(struct li_ll_t *list, void *data);
int li_ll_prepend(struct li_ll_t *list, void *data);
+// copy a linked list. !!! WARNING !!! if this function fails (returns nonzero) you MUST call li_free_ll on dst yourself!
int li_copy_list(struct li_ll_t **dst, struct li_ll_t *src, void *(*copy_data)(void*));
-
+// sort a list. compare_data should return a positive, negative or zero value of the same sign as (a-b)
+int li_sort_list(struct li_ll_t *list, int (*compare_data)(void *, void*));
diff --git a/lichen.test.c b/lichen.test.c
index 946e0be..6329992 100644
--- a/lichen.test.c
+++ b/lichen.test.c
@@ -175,6 +175,30 @@ LILY_TEST("copy a list") {
#include LILY_PUSH_TEST()
+int compare_data(void *va, void *vb) {
+ int a = *((int*)va);
+ int b = *((int*)vb);
+ return a - b;
+}
+LILY_TEST("sort a list") {
+ li_ll_t *list = li_alloc_ll();
+ int arr[] = { 5, 6, 3, 2, 9, 8, 1, 0, 4, 7 };
+ for (size_t i=0; i<sizeof(arr)/sizeof(int); i++) {
+ li_ll_append(list, arr+i);
+ }
+ li_sort_list(list, compare_data);
+ li_llnode_t *n = list->head;
+ for (size_t i=0; i<sizeof(arr)/sizeof(int); i++) {
+ INFO("[%d] original: %d / sort: %d", i, arr[i], *((int*)n->data));
+ CHECK_EQ((int)i, *((int*)n->data), "%d");
+ n = n->next;
+ }
+
+ li_free_ll(list, do_nothing);
+}
+#include LILY_PUSH_TEST()
+
+
#define LILY_FILE_END
#include LILY_REGISTER_TESTS()