Implementa inserção ordenada em lista
authorThadeu Lima de Souza Cascardo <cascardo@cascardo.eti.br>
Sat, 25 Jul 2015 19:30:06 +0000 (16:30 -0300)
committerThadeu Lima de Souza Cascardo <cascardo@cascardo.eti.br>
Sat, 25 Jul 2015 20:09:53 +0000 (17:09 -0300)
list.c
list.h
listtest.c

diff --git a/list.c b/list.c
index 6671b2e..87913c4 100644 (file)
--- a/list.c
+++ b/list.c
@@ -97,6 +97,16 @@ out:
        return -1;
 }
 
+int list_insert_ordered(struct list **list, void *val, sort_function_t *fn)
+{
+       struct list *l = *list;
+       int i;
+       for (i = 0; i < l->len; i++)
+               if (fn(l->items[i].val, val) >= 0)
+                       return list_insert(list, i, val);
+       return list_add(list, val);
+}
+
 void * list_get(struct list *list, int pos)
 {
        unsigned int i;
diff --git a/list.h b/list.h
index cebc3d4..bf09f6f 100644 (file)
--- a/list.h
+++ b/list.h
 #define _LIST_H
 
 typedef void (free_function_t)(void *);
+typedef int (sort_function_t)(void *, void *);
 struct list;
 
 struct list * list_new(void);
 int list_add(struct list **list, void *val);
 int list_insert(struct list **list, int pos, void *val);
+int list_insert_ordered(struct list **list, void *val, sort_function_t *fn);
 void * list_get(struct list *list, int pos);
 void list_free(struct list *list, free_function_t *ifree);
 
index b449fe4..d40b78b 100644 (file)
@@ -28,6 +28,24 @@ static char *names[] = {
        "english",
 };
 
+static char *sorting[] = {
+       "1",
+       "5",
+       "0",
+       "3",
+       "9",
+};
+
+static char *sorted[] = {
+       "0",
+       "1",
+       "3",
+       "5",
+       "9",
+};
+
+#define ALEN(x) (sizeof(x)/sizeof(x[0]))
+
 int main(int argc, char **argv)
 {
        struct list *l;
@@ -78,5 +96,18 @@ int main(int argc, char **argv)
        printf("Multiple insertion at end ordering list test pass\n");
        fflush(stdout);
 
+       l = list_new();
+       for (i = 0; i < ALEN(sorting); i++) {
+               list_insert_ordered(&l, strdup(sorting[i]),
+                                   (sort_function_t *) strcmp);
+       }
+       for (i = 0; i < ALEN(sorted); i++) {
+               if (strcmp(list_get(l, i), sorted[i]))
+                       return 1;
+       }
+       list_free(l, free);
+       printf("Ordered insertion list test pass\n");
+       fflush(stdout);
+
        return 0;
 }