Programming and Application(编程与应用)


Content(目录)




Linux


MySQL
Office















 
PCNow 30-Day Free Trial, Remote PC Access
 
Logo_234x60

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


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

前几天,一个朋友写信来,要求我帮忙修改字符串排序的程序段,这段程序中错误太多,我基本上重写了全部代码,现将调试通过的源代码公布于此,供需要的朋友使用。
该段代码要求用户输入5个字符串,然后对它们进行排序(使用气泡法),然后检查重复的字符串,并删除之,这样每个输出的字符串都是唯一的。注意本例程的排序结果是从大到小。
#include<stdio.h>
#include<string.h>
#include<malloc.h>
#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;
  }
}
下载源代码 ©董占山Zhanshan Dong

Post comments(留言)

Name(名字):

Comment(内容):


由Google提供

SunfineData Products|U's Bargain Network|Contact Me(与我联系)
© 1998-, 董占山, 版权所有, 欢迎转载文章链接。
转载文章和软件请注明出处(http://articles.sunfinedata.com/)。