#include <stdio.h>
#include <stdlib.h>
struct node
{ char *data; /*接点的数据域为指针,或理解为字符数组*/
struct node *next;
}*head,*p,*q;
int main() /*假设文件中有许多单词,将单词从文件中读出,放到链表中,按字母升序实现*/
{ int i;
char ch;
FILE *fp;
if(!(fp=fopen("filename","r"))) /*以只读方式打开文件 */
{ printf("cannot open the file!");
return 0;
}
head=(node *)malloc(sizeof(struct node)); /*构建单向链表的头结点 */
head->data[0]='a'; /*把头结点的第一个单元强行赋值为a */
while((ch=fgetc(fp))!=EOF)/*读一个字符并判断文件是否 结束*/
{
while(ch==' '){ch=fgetc(fp);} /*排除连续的多个空格 */
if(ch<'z'){ch+=0x20;} /*如果是大写字母,则改为小写字母 */
i=0;
q=(node *)malloc(sizeof(struct node)); /*申请一个结点用来存放新单词 */
while(ch=fgetc(fp)!=' ') /*把非空格字符放入q结点*/
{
q->data[i]=ch; /*把新读取的新字符存入新结点数据域(字符数组)的第i个单元 */
i++;
}
for(p=head;q->data>p->next->data;p=p->next); /*把新结点插入排序 */
q->next=p->next;
p->next=q;
} fclose(fp); /*关闭文件*/
p=head->next;
for (;!p->next ;p=p->next) {printf(p->data);}/*打印结果*/
free(head); /*释放头结点*/
return 1;
}