oxedyne/fe2o3/fe2o3_text/tests/detect_corpus/c/pointers_structs.txt
1.6 KiB, 1 run
created by r1870400018:11938, which is this file's identity for as long as the history lasts, whatever it is later renamed to
download · who wrote it · its history
| 1 | #include <stdio.h> |
| 2 | #include <stdlib.h> |
| 3 | #include <string.h> |
| 4 | |
| 5 | typedef struct node { |
| 6 | int data; |
| 7 | struct node *left; |
| 8 | struct node *right; |
| 9 | } node_t; |
| 10 | |
| 11 | node_t *node_new(int data) { |
| 12 | node_t *n = malloc(sizeof(node_t)); |
| 13 | if (n == NULL) return NULL; |
| 14 | n->data = data; |
| 15 | n->left = NULL; |
| 16 | n->right = NULL; |
| 17 | return n; |
| 18 | } |
| 19 | |
| 20 | node_t *bst_insert(node_t *root, int data) { |
| 21 | if (root == NULL) return node_new(data); |
| 22 | if (data < root->data) |
| 23 | root->left = bst_insert(root->left, data); |
| 24 | else if (data > root->data) |
| 25 | root->right = bst_insert(root->right, data); |
| 26 | return root; |
| 27 | } |
| 28 | |
| 29 | node_t *bst_find(node_t *root, int data) { |
| 30 | while (root != NULL) { |
| 31 | if (data == root->data) return root; |
| 32 | if (data < root->data) |
| 33 | root = root->left; |
| 34 | else |
| 35 | root = root->right; |
| 36 | } |
| 37 | return NULL; |
| 38 | } |
| 39 | |
| 40 | void bst_inorder(node_t *root, void (*visit)(int)) { |
| 41 | if (root == NULL) return; |
| 42 | bst_inorder(root->left, visit); |
| 43 | visit(root->data); |
| 44 | bst_inorder(root->right, visit); |
| 45 | } |
| 46 | |
| 47 | void bst_free(node_t *root) { |
| 48 | if (root == NULL) return; |
| 49 | bst_free(root->left); |
| 50 | bst_free(root->right); |
| 51 | free(root); |
| 52 | } |
| 53 | |
| 54 | static void print_int(int x) { |
| 55 | printf("%d ", x); |
| 56 | } |
| 57 | |
| 58 | int main(void) { |
| 59 | int values[] = {5, 3, 7, 1, 4, 6, 8}; |
| 60 | size_t n = sizeof(values) / sizeof(values[0]); |
| 61 | |
| 62 | node_t *root = NULL; |
| 63 | for (size_t i = 0; i < n; i++) |
| 64 | root = bst_insert(root, values[i]); |
| 65 | |
| 66 | printf("inorder: "); |
| 67 | bst_inorder(root, print_int); |
| 68 | printf("\n"); |
| 69 | |
| 70 | node_t *found = bst_find(root, 4); |
| 71 | if (found) |
| 72 | printf("found: %d\n", found->data); |
| 73 | |
| 74 | bst_free(root); |
| 75 | return 0; |
| 76 | } |