skiplist/examples/slm.c

88 lines
2 KiB
C
Raw Normal View History

2024-03-17 14:40:59 +00:00
#include <stddef.h>
#include <stdlib.h>
#include <stdint.h>
2024-03-18 15:06:49 +00:00
#include <errno.h>
2024-03-17 14:40:59 +00:00
#include "../include/sl.h"
/*
* SKIPLIST EXAMPLE:
*
* This example creates a Skiplist keys and values are integers.
2024-03-18 15:06:49 +00:00
* 'slex' - meaning: SkipList EXample
2024-03-17 14:40:59 +00:00
*/
/* Create a type of Skiplist that maps int -> int. */
2024-03-18 15:06:49 +00:00
struct slex_node {
2024-03-17 14:40:59 +00:00
int key;
int value;
2024-03-18 15:06:49 +00:00
SKIP_ENTRY(slex_node) entries;
2024-03-17 14:40:59 +00:00
};
2024-03-18 15:06:49 +00:00
SKIP_HEAD(slex, slex_node);
2024-03-17 14:40:59 +00:00
2024-03-18 15:06:49 +00:00
/* Generate all the access functions for our type of Skiplist. */
SKIP_DECL(slex, api_, entries, {
2024-03-17 14:40:59 +00:00
(void)aux;
if (a->key < b->key)
2024-03-18 15:06:49 +00:00
return -1;
2024-03-17 14:40:59 +00:00
if (a->key > b->key)
2024-03-18 15:06:49 +00:00
return 1;
2024-03-17 14:40:59 +00:00
return 0;
2024-03-18 15:06:49 +00:00
})
2024-03-17 14:40:59 +00:00
int main() {
/* Allocate and initialize a Skiplist. */
2024-03-18 15:06:49 +00:00
slex_t _list = SKIP_HEAD_DEFAULT_INITIALIZER(__skip_key_compare_slex);
_list.slh_tail = (struct slex_node *)&_list.slh_head; // TODO...
/* Dynamic allocation, init. */
slex_t *list = (slex_t *)malloc(sizeof(slex_t));
SKIP_DEFAULT_INIT(list, __skip_key_compare_slex, slex_node, entries);
2024-03-17 14:40:59 +00:00
#ifdef STATIC_INIT
2024-03-18 15:06:49 +00:00
free(list);
slex_t *list = &_list;
#else
2024-03-17 14:40:59 +00:00
#endif
2024-03-18 15:06:49 +00:00
struct slex_node *n;
SKIP_ALLOC_NODE(list, n, slex_node, entries);
n->key = -1;
n->value = -1;
api_skip_insert_slex(list, n);
2024-03-17 14:40:59 +00:00
/* Insert 10 key/value pairs into the list. */
for (int i = 0; i < 10; i++) {
2024-03-18 15:06:49 +00:00
SKIP_ALLOC_NODE(list, n, slex_node, entries);
2024-03-17 18:12:56 +00:00
n->key = i;
n->value = i;
2024-03-18 15:06:49 +00:00
api_skip_insert_slex(list, n);
2024-03-17 14:40:59 +00:00
}
#if 0
/* Delete a specific element in the list. */
2024-03-18 15:06:49 +00:00
struct slex_node query;
2024-03-17 14:40:59 +00:00
query.key = 4;
2024-03-18 15:06:49 +00:00
struct slex_node *removed = SKIP_REMOVE(list, q, entries);
2024-03-17 14:40:59 +00:00
free(removed);
/* Forward traversal. */
SKIP_FOREACH(np, &head, entries)
np-> ...
/* Reverse traversal. */
SKIP_FOREACH_REVERSE(np, &head, skiphead, entries)
np-> ...
/* Skiplist Deletion. */
while (!SKIP_EMPTY(&head)) {
n1 = SKIP_FIRST(&head);
SKIP_REMOVE(&head, n1, entries);
free(n1);
}
/* Faster Skiplist Deletion. */
n1 = SKIP_FIRST(&head);
while (n1 != NULL) {
n2 = SKIP_NEXT(n1, entries);
free(n1);
n1 = n2;
}
SKIP_INIT(&head);
#endif
return 0;
}