-
Notifications
You must be signed in to change notification settings - Fork 0
/
keylist.c
95 lines (83 loc) · 1.93 KB
/
keylist.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include <stdio.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
#include <limits.h>
#include "keylist.h"
#include "zmalloc.h"
kl *kl_create(void) {
kl *head = zmalloc(sizeof(kl));
head->first = NULL;
return head;
}
void kl_destroy(kl *list) {
klnode *next;
klnode *this = list->first;
while(this) {
next = this->next;
free(this);
this = next;
}
free(list);
}
void *kl_find(const kl *list, int key) {
klnode **nodep = klnode_locate(list, key);
klnode *node = *nodep;
if(node && node->key == key) return node->value;
return NULL;
}
int kl_remove(kl *list, int key) {
klnode **nodep = klnode_locate(list, key);
klnode *node = *nodep;
/* check if we found it or not */
if(node && node->key == key) {
*nodep = node->next;
free(node);
return 1;
}
return 0;
}
void kl_insert(kl *list, int key, void *value) {
klnode *new;
klnode **nodep = klnode_locate(list, key);
klnode *node = *nodep;
/* exact match, update */
if(node && node->key == key) {
node->value = value;
return;
}
/* otherwise insert */
new = klnode_create(key, value, node);
*nodep = new;
}
void kl_output(const kl *list) {
klnode *node = list->first;
while(node) {
printf("%d-->", node->key);
node = node->next;
}
printf("#\n");
}
int kl_len(const kl *list) {
int len = 0;
klnode *node = list->first;
while(node) {
len++;
node = node->next;
}
return len;
}
static klnode *klnode_create(int key, void *value, klnode *next) {
klnode *new = zmalloc(sizeof(klnode));
new->key = key;
new->value = value;
new->next = next;
return new;
}
static klnode **klnode_locate(const kl *list, int key) {
klnode **nodep = (klnode**)&list->first;
while(*nodep && (*nodep)->key < key) {
nodep = &(*nodep)->next;
}
return nodep;
}