第一次写 c 程序,不保证正确,请自己 debug
程序假设单词是 a to z 组成
用的 bst counting, 然后 导出来 qsort
#include
#include
struct _node;
typedef struct _node {
int cc;
char c;
struct _node * n[26];
struct _node * fa;
} node;
void addToTree(node * root, node * r, const char * p1, const char * p2) {
int t;
int i;
if (p1 == p2) {
if (r->cc == 0) root->cc++;
r->cc++;
return;
}
t = (*p1) - (int)'a';
if (r->n[t] == NULL) {
r->n[t] = (node *)malloc(sizeof(node));
r->n[t]->cc = 0;
r->n[t]->fa = r;
r->n[t]->c = (*p1);
for (i = 0; i < 26; i++) r->n[t]->n[i] = NULL;
}
addToTree(root, r->n[t], p1 + 1, p2);
};
void moveAll(node ** all, node * r, int * index) {
int i;
if (r->cc > 0) {
all[*index] = r;
(*index)++;
}
for (i = 0; i < 26; i++) if (r->n[i] != NULL)
moveAll(all, r->n[i], index);
};
int nodeCmp (const void * a, const void * b) {
return ( (*((node**)b))->cc - (*((node**)a))->cc );
}
void freeTree( node * r ) {
int i;
for (i = 0; i < 26; i++) if (r->n[i] != NULL) freeTree(r->n[i]);
free(r);
}
void counting(const char * str, FILE *fp) {
const char * p1 = str;
const char * p2;
int i, j, k;
int index;
char * tmpStr;
node * root;
node * t1;
node ** all;
if (fp == NULL) return;
root = (node*)malloc(sizeof(node));
root->cc = 0;
root->fa = NULL;
root->c = 0;
for (i = 0; i < 26; i++) root->n[i] = NULL;
while ((*p1) == ' ') p1++;
if (*p1 == '\0') { return; }
p2 = p1;
while (p2 != '\0') {
p2++;
if (*p2 == ' ' || *p2 == '\0') {
addToTree(root, root, p1, p2);
p1 = p2;
while ((*p1) == ' ') p1++;
if (*p1 == '\0') break;
p2 = p1;
}
}
all = (node **)malloc( (root->cc + 1) * sizeof(node) );
index = 0;
moveAll(all, root, &index);
qsort(all + 1, index - 1, sizeof(node *), nodeCmp);
for (i = 1; i < index; i++) {
j = 0;
t1 = all[i];
while (t1->fa != NULL) {
t1 = t1->fa;
j++;
}
tmpStr = (char *)malloc((j + 1) * sizeof(char));
tmpStr[j] = '\0';
t1 = all[i];
k = j - 1;
while (t1->fa != NULL) {
tmpStr[k--] = t1->c;
t1 = t1->fa;
}
fprintf(fp, "%s\t: %d\n", tmpStr, all[i]->cc);
free(tmpStr);
tmpStr = NULL;
}
free(all);
freeTree(root);
fprintf(fp, "End\n");
};
int main() {
const char * targetStr = "aa bb bb bc bc bc ad ad ad ad ad aaa";
FILE *fp;
fp = fopen("test.out", "w");
if (fp == NULL) {
fprintf(stderr, "File open error!\n");
exit(1);
};
counting(targetStr, fp);
fclose(fp);
return 0;
}