字典樹, 字串排序
阿新 • • 發佈:2021-10-04
#include <stdio.h> #include <stdlib.h> #include <string.h> #define MAX_N 26 typedef struct Node { int flag; struct Node *next[MAX_N]; } Node; void clear(Node *root) { if (!root) return ; for (int i = 1; i < MAX_N; i++) clear(root->next[i]); free(root); return ; } Node *getNewNode() { Node *p = (Node *)malloc(sizeof(Node)); p->flag = 0; for (int i = 0; i < MAX_N; i++) p->next[i] = 0; return p; } Node *insert(Node *root, char *a) { if (!root) root = getNewNode(); Node *p = root; for (int i = 0; a[i]; i++) { p->next[a[i] - 'a'] || (p->next[a[i] - 'a'] = getNewNode()); p = p->next[a[i] - 'a']; } p->flag = 1; return root; } int fin(Node *root, char *a, int s) { if (!root) return 0; if (!s && root->flag) return 1; return fin(root->next[a[0] - 'a'], a + 1, s - 1); } void output(Node *root, char *c, int s) { if (!root) return ; root->flag && (c[s] = 0, printf("%s\n", c)); for (int i = 0; i < MAX_N; i++) { c[s] = i + 'a'; root->next[i] && (output(root->next[i], c, s + 1), 0); } return ; } int main() { int op; char buff[1000] = {0}; Node *root = getNewNode(); while (~scanf("%d", &op)) { op - 2 && scanf("%s", buff); switch (op) { case 2: printf("排序: \n"), output(root, buff, 0); break; case 0: printf("\n插入%s\n", buff), insert(root, buff); break; case 1: printf("\n查詢%s == %d\n", buff, fin(root, buff, strlen(buff))); } } return 0; }