【0501】有序列表合并

#include <stdio.h>
#include <stdlib.h>
#define MAXLEN 100


void openfile(char *str,int list[])
{
	FILE *fp;
	int i=0,j=0;
	int temp;
	char ch;
	if((fp = fopen(str,"r"))==NULL)
	{

		printf("can't open %s\n",str);
		exit(0);
	}
	while((fscanf(fp,"%d",&temp))==1)
	{
		list[++i] = temp;
		fscanf(fp,",",&ch);

	}
	list[0] = i;
	for(i=1;i<=list[0];i++)
	{

		printf("%d ",list[i]);
	}
	printf("\n");
	if(fclose(fp)!=0)
		printf("Error in closing file %s/n",str);
}
void write(int list[],char *str)
{
	FILE *fp;
	int i=1;
	int temp;
	if((fp = fopen(str,"w"))==NULL)
	{

		printf("can't open %s\n",str);
		exit(0);
	}
	while(i<=list[0])
	{
		fprintf(fp,"%d ",list[i]);
		i++;
	}
	if(fclose(fp)!=0)
		printf("Error in closing file %s/n",str);

}

void sort(int list1[],int list2[],int list[])
{

	int i=1,j=1,k=1,temp;
	while(i<=list1[0]&&j<=list2[0])
	{

		if(list1[i]<=list2[j])
		{

			list[k] = list1[i];
			i++;
			k++;
		}
		else
		{
			list[k] = list2[j];
			j++;
			k++;
		}
	}
	while(i<=list1[0])
	{
		list[k++] = list1[i++];

	}
	while(j<=list2[0])
	{
		list[k++] = list2[j++];

	}
	list[0] = k-1;
	for(i=1;i<=list[0];i++)
	{

		printf("%d ",list[i]);
	}
}
int main()
{
	int list1[MAXLEN];
	int list2[MAXLEN];
	int list[MAXLEN];
	openfile("A.txt",list1);
	openfile("B.txt",list2);
	sort(list1,list2,list);
	write(list,"c.txt");
	return 0;
}

猜你喜欢

转载自blog.csdn.net/yong_ss/article/details/86616858
今日推荐