#include <stdio.h>
#include <stdlib.h>
#include <conio.h>
//链表结构
struct list
{
char ch;
struct list *next;
};
//为链表结构创建别名
typedef struct list *LISTPTR;
//函数原形
LISTPTR addToList(char ch,LISTPTR first);
void freeMemorgList(LISTPTR first);
void printList(LISTPTR first);
//程序入口
void main()
{
LISTPTR first = NULL;
int i = 0;
char ch;
char trash[256];
while(i++ < 7)
{
ch = 0;
printf("Enter %d",i);
do
{
printf("Must to 'a'-'z'");
ch = getc(stdin);
//从键盘得到一个字符
gets(trash);
//清空键盘缓冲区多余字符
}while((ch < 'a' || ch > 'z') && (ch < 'A' || ch > 'Z'));
first = addToList(ch,first);
}
printList(first);
freeMemorgList(first);
}
//添加链表节点函数并对节点排序
LISTPTR addToList(char ch,LISTPTR first)
{
LISTPTR new_rec = NULL;
LISTPTR tmp_rec = NULL;
LISTPTR prev_rec = NULL;
new_rec = (LISTPTR)malloc(sizeof(list));
if(!new_rec)
{
puts("memory error..");
getch();
exit(1);
}
new_rec->ch = ch;
new_rec->next = NULL;
if(first==NULL)
{
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;
/*if(new_rec->next != prev_rec->next)//调试代码
{
puts("ERROR");
getch();
exit(0);
}*/
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 printList(LISTPTR first)
{
int counter =1;
while(first != NULL)
{
printf("%X\t",first);
printf("%d\t%c\t",counter++,first->ch);
printf("%X\n",first->next);
first = first->next;
}
}
//释放链表占用的全部内存
void freeMemorgList(LISTPTR first)
{
LISTPTR cur_ptr,next_rec;
cur_ptr = first;
while(cur_ptr != NULL)
{
next_rec = cur_ptr->next;
free(cur_ptr);
cur_ptr = next_rec;
}
}