git.fiddlerwoaroof.com
Browse code

feat: c list thing

Ed Langley authored on 29/10/2020 23:40:32
Showing 1 changed files
1 1
new file mode 100644
... ...
@@ -0,0 +1,70 @@
1
+#include <stdio.h>
2
+#include <stdlib.h>
3
+
4
+typedef unsigned int item_type;
5
+typedef struct list {
6
+  item_type item;
7
+  struct list * next;
8
+} list;
9
+
10
+list * search_list(list *l, item_type x) {
11
+  if (l == NULL) return NULL;
12
+
13
+  if (l->item == x) {
14
+    return l;
15
+  } else {
16
+    return search_list(l->next, x);
17
+  }
18
+}
19
+
20
+void insert_list(list **l, item_type x) {
21
+  list *p;
22
+
23
+  p = malloc(sizeof(list) );
24
+  p->item = x;
25
+  p->next = *l;
26
+  *l = p;
27
+}
28
+
29
+list *predecessor_list(list *l, item_type x) {
30
+  if ((l == NULL) || (l->next == NULL)) {
31
+    printf("Error: predecessor sought on null list.\n");
32
+    return NULL;
33
+  }
34
+
35
+  if ((l->next)->item == x) {
36
+    return l;
37
+  } else {
38
+    return predecessor_list(l->next, x);
39
+  }
40
+}
41
+
42
+delete_list(list **l, item_type x) {
43
+  list *p;
44
+  list * pred;
45
+
46
+  p = search_list(*l, x);
47
+  if (p != NULL) {
48
+    pred = predecessor_list(*l, x);
49
+    if (pred == NULL) {
50
+      *l = p->next;
51
+    } else {
52
+      pred->next = p->next;
53
+    }
54
+
55
+    free(p);
56
+  }
57
+}
58
+
59
+item_type i(list *l) {
60
+  if (l == NULL) return -1;
61
+  return l->item;
62
+}
63
+int main() {
64
+  list *l = NULL;
65
+  insert_list(&l, 123);
66
+  insert_list(&l, 234);
67
+  delete_list(&l, 123);
68
+  printf("%u\n", i(search_list(l, 123)));
69
+  return 42;
70
+}