#include <stdlib.h>
#include <assert.h>
#include <stdio.h>
#include <string.h>
#define TRUE 1
#define FALSE 0
/* 定义了一个单词链表,存放以该字母开头的单词链表 */
typedef struct WORD
{
char *word;
struct WORD *next;
}Word;
/* 定义一个以26个字母开头的链表 */
typedef struct LIST
{
char letter;
struct LIST *next;
Word* word_list;
}list;
/* 插入函数 */
int concordance_insert( list** listp, char *the_word)
{
char first_char;
list *current_list;
Word *current_word;
Word **wordp;
int comparison;
Word *new_word;
first_char = *the_word;//取出要插入单词的第一个字母
if( !islower( first_char ) )//判断该单词是否有效
return FALSE;
/* 插入字母表 */
while( ( current_list = *listp ) != NULL
&& current_list -> letter < first_char )//判断插入的位置
listp = ¤t_list -> next;
if( current_list == NULL || current_list -> letter > first_char )
{
list *new_list;
new_list = ( list* )malloc( sizeof( list ) );
if( new_list == NULL )
return FALSE;
new_list -> letter = first_char;//创建一个字母链表
new_list -> word_list = NULL;//该字母链表下面无单词
new_list -> next = current_list;//插入的新链表指向后一节链表
*listp = new_list;//插入新链表前一节链表指向当前新链表
current_list = new_list;//把新链表的地址给到current_list,以供下面使用
}
/* 检查该单词是否存在于单词链表中 */
wordp = ¤t_list -> word_list;
while( ( current_word = *wordp ) != NULL )
{
comparison = strcmp( current_word -> word, the_word );//给当前单词表排序
if( comparison >= 0)
break;
wordp = ¤t_word -> next;
}
if( comparison == 0 )//若该单词存在于单词链表中返回0
return FALSE;
/* 创建单词链表 */
new_word = ( Word* )malloc( sizeof( Word ) );
if( new_word == NULL )
return FALSE;
new_word -> word = malloc( strlen( the_word ) + 1 );
if( new_word == NULL )
return FALSE;
strcpy( new_word -> word, the_word );
new_word -> next = current_word;//插入的新单词链表指向后一节单词链表
*wordp = new_word;//插入新单词链表前一节单词链表指向当前新单词链表
return TRUE;
}
void main()
{
list *root ;
root = NULL;
concordance_insert( &root, "bbq");
concordance_insert( &root, "aq");
concordance_insert( &root, "aq");
printf( "%s\n", root -> word_list -> word);
printf( "%s\n", root -> next -> word_list -> word );
}