C语言对字符串进行排序的程序(气泡法)

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

该段代码要求用户输入5个字符串,然后对它们进行排序(使用气泡法),然后检查重复的字符串,并删除之,这样每个输出的字符串都是唯一的。注意本例程的排序结果是从大到小。

#include
#include
#include
#define N 20 // the length of English words

struct node {
char en[N];
struct node *next;
};

void print(struct node *p);
void sort(struct node *p);
void del(struct node *p);
void swap(struct node *s1, struct node *s2);

void main() {
struct node *h=NULL, *p, *p1;
char a[N];
int z = 0;
while(z<5) {
printf("Input the word:");
gets(a);
p=(struct node *) malloc(sizeof(struct node));
strcpy(p->en,a);
if(h==0) {
h = p;
p1 = p;
}
else {
p1->next = p;
p1 = p;
}
z = z + 1;
}
p->next = NULL;
// print(h);
sort(h);
// print(h);
del(h);
print(h);
}

void sort(struct node *p) {
// bubble method
struct node *p1, *p2;
p1 = p;
while(p1) {
p2 = p1->next;
while(p2) {
if(strcmp((p2->en),(p1->en))>0) {
swap(p1,p2);
}
p2 = p2->next;
}
p1 = p1->next;
}
}

void swap(struct node *s1, struct node *s2) {
struct node temp1,temp2;
temp1 = *s1;
temp1.next = s2->next;
temp2 = *s2;
temp2.next = s1->next;
*s1 = temp2;
*s2 = temp1;
}

void del(struct node *p) {
struct node *p1,*p2;
p1 = p->next;
while(p1) {
p2 = p1->next;
while(p2) {
if(strcmp((p2->en),(p1->en))==0) {
p1->next = p1->next->next;
free(p2);
}
else {
break;
}
p2 = p1->next;
}
p1 = p1->next;
}
}

void print(struct node *p) {
while(p) {
puts(p->en);
p = p->next;
}
}


相关文档
最新文档