单词索引表
一个下午的时间,终于完成了。不知道大神们有没有更简洁的写法。
题目是:用链表写一个单词索引表。
程序代码:#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
struct word {
char * words;
struct word * p_word;
};
struct word_tab {
char alphaber;
struct word_tab * total;
struct word * word;
};
int index_word_tab(struct word_tab ** p_total, char word[]);
void print_word(struct word_tab ** p_total);
int getword(char word[],int n);
int main(void)
{
struct word_tab *p;
struct word_tab **kp;
char word1[50];
p = NULL;
kp = &p;
while(getword(word1,50) > 0)
index_word_tab(kp, word1);
print_word(kp);
getchar();
return 0;
}
int getword(char word[], int n)
{
int i,c;
for(i = 0; i < n - 1 && (c = getchar()) != EOF && !isspace(c);i++)
word[i] = c;
word[i] = '\0';
return i;
}
int index_word_tab(struct word_tab ** p_total, char word[])
{
int determine(char word[]);
struct word_tab * next;
struct word_tab * new_total;
struct word * next_word;
struct word * new_word;
struct word ** kp_word;
char w;
if(determine(word) < 0)
{
printf("ERORR: %s\n",word);
return 0;
}
w = tolower(word[0]);
while((next = *p_total) != NULL && next->alphaber < w)
p_total = &next->total;
if(next == NULL || next->alphaber != w)
{
new_total = (struct word_tab *)malloc(sizeof(struct word_tab));
if (new_total == NULL)
return 0;
*p_total = new_total;
new_total->total = next;
new_total->alphaber = w;
new_total->word = NULL;
}
kp_word = &(*p_total)->word;
while ((next_word = *kp_word) != NULL && strcmp(next_word->words, word) <= 0)
{
if (strcmp(next_word->words, word) == 0)
return 0;
kp_word = &next_word->p_word;
}
new_word = (struct word *)malloc(sizeof(struct word));
if (new_word == NULL)
return 0;
*kp_word = new_word;
new_word->p_word = next_word;
new_word->words = strdup(word);
return 1;
}
void print_word(struct word_tab ** p_total)
{
struct word_tab * next;
struct word * word_next;
int i;
while((next = *p_total) != NULL)
{
for(word_next = next->word,i = 0; word_next != NULL;word_next = word_next->p_word,i++)
printf("%s%c", word_next->words,((i+1)%8)?' ':'\n');
printf("\n\n");
p_total = &next->total;
}
}
int determine(char word[])
{
int i,j;
j = strlen(word);
for(i = 0; isalpha(word[i]);i++)
;
if(i == j)
return i;
else
return -1;
}[此贴子已经被作者于2017-2-18 11:42编辑过]







