一个链表程序,不知道为什么不行
程序代码:#include <stdlib.h>
#include <stdio.h>
#ifndef NULL
#define NULL 0
#endif
struct list
{
char *ch;
struct list *next_rec;
};
typedef struct list LIST;
typedef LIST *LISTPTR;
LISTPTR add_to_list(char *, LISTPTR);
void show_list(LISTPTR);
void free_memory_list(LISTPTR);
LISTPTR first = NULL;
int main(void)
{
int i = 0;
char *ch;
ch = (char *)malloc(40);
while(i++ < 5)
{
printf("\nEnter name %d,", i);
do
{
printf("\nPlease enter a name(<=40): ");
gets(ch);
}while( (*ch < 'a' || *ch > 'z') && ( *ch < 'A' || *ch > 'Z') );
add_to_list(ch, first);
}
show_list(first);
free_memory_list(first);
return 0;
}
LISTPTR add_to_list( char *ch, LISTPTR first)
{
LISTPTR new_rec = NULL;
LISTPTR tmp_rec = NULL;
LISTPTR prev_rec = NULL;
if((new_rec = (LISTPTR)malloc(sizeof(LIST)) ) == NULL)
{
fprintf(stderr, "\nUnable to allocate memory!\n");
exit(1);
}
new_rec->ch = ch;
new_rec->next_rec = NULL;
if(first == NULL)
{
first = new_rec;
new_rec->next_rec = NULL;
}
else
{
if(strcmp(new_rec -> ch, first -> ch) < 0)
{
new_rec -> next_rec = first;
first = new_rec;
}
else
{
while ( tmp_rec -> next_rec != NULL)
{
if( strcmp(new_rec->ch, tmp_rec->ch) < 0)
{
new_rec->next_rec = tmp_rec;
if(new_rec->next_rec != prev_rec->next_rec)
{
fprintf(stderr, "ERROR");
getc(stdin);
exit(1);
}
prev_rec->next_rec = new_rec;
break;
}
else
{
tmp_rec = first -> next_rec;
prev_rec = prev_rec->next_rec;
}
}
if(tmp_rec->next_rec == NULL)
{
if(strcmp(new_rec->ch, tmp_rec->ch) < 0)
{
new_rec->next_rec = tmp_rec;
prev_rec->next_rec = new_rec;
}
else
{
tmp_rec = tmp_rec -> next_rec;
prev_rec = prev_rec -> next_rec;
}
}
}
}
return(first);
}
void show_list(LISTPTR first)
{
LISTPTR cur_ptr;
int counter = 1;
printf("\n\nRec addr Position Data Next Rec addr\n");
printf("========================================\n");
cur_ptr = first;
while(cur_ptr != NULL)
{
printf(" %p ", cur_ptr);
printf(" %2i %s", counter++, cur_ptr->ch);
printf(" %p \n", cur_ptr->next_rec);
cur_ptr = cur_ptr->next_rec;
}
}
void free_memory_list(LISTPTR first)
{
LISTPTR cur_ptr, next_rec;
cur_ptr = first;
while(cur_ptr != NULL)
{
next_rec = cur_ptr->next_rec;
free(cur_ptr);
cur_ptr = next_rec;
}
}
以上是我写的程序, 不知道为什么出错









