编程技术、软件应用与系统模拟

(Programming, Applicaiton and Simulation)



本站目录

 

首页
ASP/Access/IIS
DELPHI/PASCAL
PASCAL高级编程
C语言编程实例
WORD
Excel
MATLAB
MINITAB讲座
Windows
DOS
SAS
生物系统模拟
土壤水分剖析器
其他



镜像站点

 

主站
北美镜象站
欧洲镜象站(1)
欧洲镜象站(2)

本站 Google

[搜索]  [站内导航]
座右铭:
只做有益人类的事
不做有害人类的事


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

前几天,一个朋友写信来,要求我帮忙修改字符串排序的程序段,这段程序中错误太多,我基本上重写了全部代码,现将调试通过的源代码公布于此,供需要的朋友使用。
该段代码要求用户输入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;
  }
}
下载源代码

© 1998-, 董占山, 版权所有。
转载文章请注明出处(www.sunfinedata.com/articles)。