diff options
author | Tom Ryder <tom@sanctum.geek.nz> | 2016-03-28 16:36:01 +1300 |
---|---|---|
committer | Tom Ryder <tom@sanctum.geek.nz> | 2016-03-28 16:36:58 +1300 |
commit | ad1457beb2b61fc918e4be616a9679e30729bbd4 (patch) | |
tree | 4ec30e6475db3e34eb497335b1a22f772b12fb10 | |
download | btree-ad1457beb2b61fc918e4be616a9679e30729bbd4.tar.gz btree-ad1457beb2b61fc918e4be616a9679e30729bbd4.zip |
Tinkering with simple binary trees
Trying to keep the code nice and terse. strcmp(3) usage here possibly
unsafe.
-rw-r--r-- | .gitignore | 2 | ||||
-rw-r--r-- | Makefile | 9 | ||||
-rw-r--r-- | btree-int.c | 53 | ||||
-rw-r--r-- | btree-str.c | 54 |
4 files changed, 118 insertions, 0 deletions
diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..fcb13a2 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +btree-int +btree-str diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..ec2658d --- /dev/null +++ b/Makefile @@ -0,0 +1,9 @@ +.PHONY: all clean + +CC = clang +CFLAGS = -std=c90 -Weverything + +all : btree-int btree-str + +clean : + rm -f btree-int btree-str diff --git a/btree-int.c b/btree-int.c new file mode 100644 index 0000000..8935760 --- /dev/null +++ b/btree-int.c @@ -0,0 +1,53 @@ +#include <stdio.h> +#include <stdlib.h> + +typedef struct Node { + long v; + struct Node *l; + struct Node *r; +} Node; + +void an(Node **, Node *); +void pn(Node *); + +void an(Node **r, Node *n) { + if (!*r) { + *r = n; + return; + } + if (n->v > (*r)->v) { + an(&((*r)->r), n); + } else { + an(&((*r)->l), n); + } + return; +} + +void pn(Node *n) { + if (!n) { + return; + } + if (n->l) { + pn(n->l); + } + fprintf(stdout, "%ld\n", n->v); + if (n->r) { + pn(n->r); + } + return; +} + +int main(int argc, char **argv) { + Node *r = NULL; + + for (argv++, argc--; argc; argv++, argc--) { + Node *n = malloc(sizeof(Node)); + n->v = atoi(*argv); + n->l = n->r = NULL; + an(&r, n); + } + + pn(r); + + exit(EXIT_SUCCESS); +} diff --git a/btree-str.c b/btree-str.c new file mode 100644 index 0000000..3f080a4 --- /dev/null +++ b/btree-str.c @@ -0,0 +1,54 @@ +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +typedef struct Node { + char *v; + struct Node *l; + struct Node *r; +} Node; + +void an(Node **, Node *); +void pn(Node *); + +void an(Node **r, Node *n) { + if (!*r) { + *r = n; + return; + } + if (strcmp(n->v, (*r)->v) > 0) { + an(&((*r)->r), n); + } else { + an(&((*r)->l), n); + } + return; +} + +void pn(Node *n) { + if (!n) { + return; + } + if (n->l) { + pn(n->l); + } + fprintf(stdout, "%s\n", n->v); + if (n->r) { + pn(n->r); + } + return; +} + +int main(int argc, char **argv) { + Node *r = NULL; + + for (argv++, argc--; argc; argv++, argc--) { + Node *n = malloc(sizeof(Node)); + n->v = *argv; + n->l = n->r = NULL; + an(&r, n); + } + + pn(r); + + exit(EXIT_SUCCESS); +} |