- #include <stdio.h>
- #include <stdlib.h>
- struct list
- {
- int ch;
- struct list *next;
- };
- typedef struct list LIST;
- typedef struct list *LISTPTR;
- LISTPTR add_list(int,LISTPTR);
- void show_list(LISTPTR);
- void free_list(LISTPTR);
- int main()
- {
- LISTPTR first=NULL; //head poi-nter
- int i=0;
- int ch;
- char trash[256];
- while(i++<5)
- {
- ch=0;
- printf("/n Enter character %d",&i);
- do
- {
- printf("/nMust be a to z:");
- ch=getc(stdin);
- gets(trash);
- }while((ch<'a'||ch>'z')&&(ch<'A'||ch>'Z'));
- first=add_list(ch,first);
- }
- show_list(first);
- free_list(first);
- return 0;
- }
- LISTPTR add_list(int ch,LISTPTR first)
- {
- LISTPTR new_rec =NULL;
- LISTPTR tmp_rec =NULL;
- LISTPTR prev_rec =NULL;
- new_rec=(LISTPTR)malloc(sizeof(LIST));
- if(!new_rec)
- {
- printf("/nUnable to allocate memory/n");
- exit(1);
- }
- //set new link's data
- new_rec->ch=ch;
- new_rec->next=NULL;
- if(first==NULL) //adding first link to list
- {
- first=new_rec;
- new_rec->next=NULL;
- }
- else
- {
- if(new_rec->ch < first->ch)
- {
- new_rec->next=first;
- first=new_rec;
- }
- else
- {
- tmp_rec=first->next;
- prev_rec=first;
- if(tmp_rec==NULL)
- {
- prev_rec->next=new_rec;
- }
- else
- {
- while((tmp_rec->next!=NULL))
- {
- if(new_rec->ch < tmp_rec->ch)
- {
- new_rec->next=tmp_rec;
- prev_rec->next=new_rec;
- break;
- }
- else
- {
- tmp_rec=tmp_rec->next;
- prev_rec=prev_rec->next;
- }
- }
- if(tmp_rec->next==NULL)
- {
- if(new_rec->ch<tmp_rec->ch)
- {
- new_rec->next=tmp_rec;
- prev_rec->next=new_rec;
- }
- else
- {
- tmp_rec->next=new_rec;
- new_rec->next=NULL;
- }
- }
- }
- }
- }
- return (first);
- }
- void show_list(LISTPTR first)
- {
- LISTPTR cu;
- int counter=1;
- printf("/n/n Rec addr position Data Next rec addr/n");
- printf("========== ========== ============ ======/n");
- cu=first;
- while(cu!=NULL)
- {
- printf("%X ",cu);
- printf("%2i %c ",counter++,cu->ch);
- printf("%X /n",cu->next);
- cu=cu->next;
- printf("========== ========== ============ ======/n");
- }
- }
- void free_list(LISTPTR first)
- {
- LISTPTR cu,next_rec;
- cu=first;
- while(cu!=NULL)
- {
- next_rec=cu->next;
- free(cu);
- cu=next_rec;
- }
- }
add_list() 分开写还能看懂,就这样写一堆了之后看着头都大了,感觉看了半天,脑子都不够用了 。