c语言用单向链表做英语词典,单词保存在结构体数据域的字符数组中,如何根据各单词的字母顺序进行排序(从a到z),并逐一显示出来(和纸质的词典相同)
参考如下代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct StData
{
char name[30];
//int score;
};
typedef struct link_node
{
struct StData data;
struct link_node* next;
}node,*linklist;
linklist createList()
{
struct StData x;
linklist L;
char ch;
L = (linklist)malloc(sizeof(node));
if (L == NULL)
{
printf("error");
return 0;
}
linklist n,p;
p = L;
printf("请输入字符串:\n"); //输入系列并以回车结束
while(1)
{
scanf("%s",x.name);
n = (linklist)malloc(sizeof(node));
n->data = x;
n->next = NULL;
p->next = n;
p = n;
if( (ch=getchar()) == '\n') break;
}
return L;
}
void print(linklist head)
{
linklist p;
p = head->next;
while(p)
{
printf("%s ",p->data.name);
p = p->next;
}
printf("\n");
}
//排序
void BubbleSort(linklist List)
{
node * p, * q, * tail;
tail = NULL;
while((List->next->next) != tail)
{
p = List;
q = List->next;
while(q->next != tail)
{
if( strcmp(q->data.name ,q->next->data.name)> 0 )
{
p->next = q->next;
q->next = q->next->next;
p->next->next = q;
q = p->next;
}
q = q->next;
p = p->next;
}
tail = q;
}
}
//释放内存
void release(linklist head)
{
linklist p;
while(head)
{
p = head->next;
free(head);
head = p;
}
}
int main()
{
linklist head = createList();
printf("链表信息:");
print(head);
BubbleSort(head);
printf("排序后:");
print(head);
release(head);
return 0;
}
和数组一样遍历链表,strcmp比较数据域字符串大小然后交换字符串