#include <stdio.h> #include <string.h> #include <stdlib.h> #define BRANCH 1 #define LEAF 0 const int MAXN = 256; const int MAXLEN = 10000; typedef struct NODE { int type; int count; struct NODE* next[MAXN]; }NODE; NODE root; char buffer[MAXLEN]; int pos; void INSERT(const char* s) { NODE* curr; NODE* newnode; int len = strlen(s); curr = &root; for (int i = 0; i < len; i++) { if ( curr->next[s[i]] == NULL ) { newnode = (NODE *)malloc(sizeof(NODE)); memset(newnode, 0, sizeof(NODE)); curr->next[s[i]] = newnode; curr->type = BRANCH; } curr = curr->next[s[i]]; } curr->count += 1; } bool SEARCH(const char* s) { NODE* curr; int len = strlen(s); curr = &root; for (int i = 0; i < len; i++) { if ( curr->next[s[i]] == NULL ) return false; curr = curr->next[s[i]]; } if ( i == len && curr->count > 0 ) return true; return false; } void WALK(NODE* p) { if ( p->count > 0 ) { buffer[pos] = '\0'; printf("%s\n",buffer); if ( p->type == LEAF ) return; } for (int j = 0; j < MAXN; j++) { if ( p->next[j] != NULL) { buffer[pos++] = j; WALK(p->next[j]); pos--; } } } int main() { memset(&root, 0, sizeof(NODE)); INSERT("MENGMENG"); INSERT("JIONGJIONG"); INSERT("JIONG"); INSERT("AAB"); INSERT("C"); INSERT("AABDD"); INSERT("i am what i am"); INSERT("AM is my godness"); pos = 0; WALK(&root); printf("%d\n",SEARCH("AA")); printf("%d\n",SEARCH("AAB")); printf("%d\n",SEARCH("AABD")); printf("%d\n",SEARCH("AABDD")); return 0; }