( •̀ ω •́ )y( •̀ ω •́ )y精心整理C两百例【1-60例】,持续更新.....

前言

求解二维数组的最大最小元素、利用数组求前n个质数、万年历、数组排序、任意进制转换、回文数、求数组前n项和、求解钢材切割的最佳订单、通过指针比较整数大小、指向数组的指针、寻找指定元素的指针、寻找相同元素的指针、阿拉伯数字转化为罗马数字、字符替换等…

1、C的第一个程序

/* The first C programme */
#include <stdio.h>				/* 包含标准输入输出头文件 */
void main()						/* 主函数 */
{
	printf("Hello World!\n");	/* 打印输出信息 */
	getchar();
}

2、运行多个源文件

main.c

#include "print.h"

void main(void){
	printHello();
	getchar();
}

print.c

#include "print.h"

void printHello()
{
	printf("hello word!\n");
}

print.h

#include "stdio.h"

void printHello(void);

3、求整数之积

#include <stdio.h>

int main()
{
	int x,y,m;				/* 定义整型变量x,y,m */
	printf("Please input x and y");	/* 输出提示信息 */
	scanf("%d%d",&x,&y);			/* 读入两个乘数,赋给x,y变量 */
	m=x*y;					/* 计算两个乘数的积,赋给变量m */
	printf("%d * %d = %d\n",x,y,m);		/* 输出结果 */

	return 0;
}

4、比较实数大小

/* 输入两个浮点数,输出它们中的大数 */
#include <stdio.h>
int main()
{
	float x, y, c;						    /* 变量定义 */
	printf("Please input x and y:");	    /* 提示用户输入数据 */
	scanf("%f %f", &x, &y);
	c = x> y ? x : y;					    /* 计算c=max(x,y) */
	printf("MAX of (%f,%f) is %f",x,y,c);	/* 输出c */

	return 0;
}

5、字符的输出

#include <stdio.h>

int main()
{
	char ch, nch;	
	int count;	
	int k;		

	printf("Please input a string with a # in the end.\n");

	/** 循环获取字符 */
	while (scanf("%c", &ch) == 1 && ch != '#')
	{	
		// 丢弃\n
		if (ch == '\n')
			continue;
		printf("[out]:%c\n", ch);	
		printf("Please input a string with a # in the end.\n");

	}
	printf("#\n");				

	return 0;
}

6、显示变量所占字节数

#include <stdio.h>

void main()
{
	/* sizeof()
	* @func: 是保留字,它的作用是求某类型或某变量类型的字节数
	* @param: 传入类型保留字或变量;
	* return: 返回size_t类型的字节数
	*/

	/*int型在不同的机器,不同的编译器中的字节数不一样*/
	/*一般来说在TC2.0编译器中字节数为2,在VC编译器中字节数为4 */

	printf("The bytes of the variables are:\n");
	printf("int:%d bytes\n", sizeof(int));

	printf("char:%d byte\n", sizeof(char));	/* char型的字节数为1 */

	printf("short:%d bytes\n", sizeof(short));	/* short型的字节数为2 */

	printf("long:%d bytes\n", sizeof(long));	/* long型的字节数为4 */

	printf("float:%d bytes\n", sizeof(float));	/* float型的字节数为4 */

	printf("double:%d bytes\n", sizeof(double));	/* double型的字节数为8 */

	printf("long double:%d bytes\n", sizeof(long double));	/* long double型的字节数为8或10或12 */
	getchar();
}

7、自增自减运算符

<赋值过程可以理解为是>

#include <stdio.h>

void main()
{
	int a = 5, b, c, i = 10;
	b = a++;	
	c = ++b;	

	printf("a = %d, b = %d, c = %d \n", a, b, c);	/* 	a = 6, b = 6, c = 6 */
	printf("i, i++, ++i = %d, %d, %d\n", i, i++, ++i);  /* 	i, i++, i++ = 12, 11, 10 */
	printf("%d\n", ++i);							/* 13 */
	printf("%d\n", --i);							/* 12 */
	printf("(%d)\n", (i++));						/* 12 */
	printf("%d\n", i--);							/* 13 */
	printf("%d\n", -i++);							/* -12 */
	printf("%d\n", -i--);							/* -13 */
	
	getchar();
}

自增运算符源码

int& int::operator++()
{
	*this += 1;
	return *this;
}

const int int::operator++(int)
{
	int oldValue = *this;
	++(*this);
	return oldValue;
}

8、数列求和

#include <stdio.h>
#include <stdlib.h>

void main()
{
	int i, j, n;
	long sum = 0, temp = 0;

	printf("Please input a number to n:\n");
	scanf("%d", &n);
	if (n<1)
	{
		printf("The n must no less than 1!\n");
		return;
	}

	for (i = 1; i <= n; i++)
	{
		temp = 0;	
		for (j = 1; j <= i; j++)
			temp += j;
		sum += temp;
	}
	printf("The sum of the sequence(%d) is %d\n", n, sum);
	
	system("pause");
}

9、乘法口诀表

#include <stdio.h>

void main(void)
{
	int j, i;

	for (i = 1; i < 10; ++i){
		for (j = 1; j < i+1; ++j){
			printf("%4d * %d", j, i);
		}
		printf("\n");
	}
	getchar();
}

10、判断价格区间

#include <stdio.h>
#include <conio.h>

void main()
{
	int Password = 0, Number = 0, price = 58, i = 0;
	printf("\n====This is a Number Guess Game!====\n");
	while (Password != 1234)
	{
		if (i >= 3)
			return;
		i++;
		puts("Please input Password: ");
		scanf("%d", &Password);
	}

	i = 0;
	while (Number != price)
	{
		do{
			puts("Please input a number between 1 and 100: ");
			scanf("%d", &Number);
			printf("Your input number is %d\n", Number);
		} while (!(Number >= 1 && Number <= 100));
		if (Number >= 90)
		{
			printf("Too Bigger! Press any key to try again!\n");
		}
		else if (Number >= 70 && Number < 90)
		{
			printf("Bigger!\n");
		}
		else if (Number >= 1 && Number <= 30)
		{
			printf("Too Small! Press any key to try again!\n");
		}
		else if (Number > 30 && Number <= 50)
		{
			printf("Small! Press any key to try again!\n");
		}
		else
		{
			if (Number == price)
			{
				printf("OK! You are right! Bye Bye!\n");
			}
			else if (Number < price)
			{
				printf("Sorry,Only a little smaller! Press any key to try again!\n");

			}
			else if (Number > price)
				printf(" Sorry, Only a little bigger! Press any key to try again!\n");
		}

	}
}

11、模拟取款界面

#include <stdio.h>
#include<stdlib.h>
void main()
{
	char SelectKey, CreditMoney, DebitMoney;
	while (1)
	{
		do{
			puts("=========================");
			puts("|  Please select key:   |");
			puts("|  1. Quary             |");
			puts("|  2. Credit            |");
			puts("|  3. Debit             |");
			puts("|  4. Return            |");
			puts("=========================");
			SelectKey = getchar();
			//fflush(stdin);
		} while (SelectKey != '1' && SelectKey != '2' && SelectKey != '3' && SelectKey != '4');
		switch (SelectKey)
		{
		case '1':
			puts("================================");
			puts("|    Your balance is $1000.    |");
			puts("|  Press any key to return...  |");
			puts("================================");
			getchar();
			break;
		case '2':
			do{
				puts("==================================");
				puts("|   Please select Credit money:  |");
				puts("|   1. $50                       |");
				puts("|   2. $100                      |");
				puts("|   3. Return                    |");
				puts("==================================");
				CreditMoney = getchar();
				fflush(stdin);
			} while (CreditMoney != '1' && CreditMoney != '2' && CreditMoney != '3');
			switch (CreditMoney)
			{
			case '1':
				puts("=========================================");
				puts("|  Your Credit money is $50,Thank you!  |");
				puts("|         Press any key to return...    |");
				puts("=========================================");
				getchar();
				break;
			case '2':
				puts("==========================================");
				puts("|  Your Credit money is $100,Thank you!  |");
				puts("|         Press any key to return...     |");
				puts("==========================================");
				getchar();
				break;
			case '3':
				break;
			}
			break;
		case '3':
			do{
				puts("====================================");
				puts("|   Please select Debit money:     |");
				puts("|   1. $50                         |");
				puts("|   2. $100                        |");
				puts("|   3. $500                        |");
				puts("|   4. $1000                       |");
				puts("|   5. Return                      |");
				puts("====================================");
				DebitMoney = getchar();
				fflush(stdin);
			} while (DebitMoney != '1' && DebitMoney != '2' && DebitMoney != '3' \
				&& DebitMoney != '4' && DebitMoney != '5');
			switch (DebitMoney)
			{
			case '1':
				puts("===========================================");
				puts("|   Your Debit money is $50,Thank you!    |");
				puts("|        Press any key to return...       |");
				puts("===========================================");
				getchar();
				break;
			case '2':
				puts("===========================================");
				puts("|   Your Debit money is $100,Thank you!   |");
				puts("|        Press any key to return...       |");
				puts("===========================================");
				getchar();
				break;
			case '3':
				puts("===========================================");
				puts("|   Your Debit money is $500,Thank you!   |");
				puts("|        Press any key to return...       |");
				puts("===========================================");
				break;
			case '4':
				puts("===========================================");
				puts("|   Your Debit money is $1000,Thank you!  |");
				puts("|        Press any key to return...       |");
				puts("===========================================");
				break;
			case '5':
				break;
			}
			break;
		case '4':
			puts("================================");
			puts("|   Thank you for your using!  |");
			puts("|            Good bye!         |");
			puts("================================");
			return;
		}
	}
}

14、用一维数组统计学生成绩


#include <stdio.h>
#include <stdlib.h>

void main()
{	
	int score[1024] = { 0 };
	int n=0, i;
	printf("Please enter number:");
	scanf("%d", &n);

	for (i = 0; i < n; ++i){
		printf("Please enter the score of %d:", i + 1);
		scanf("%d", &score[i]);
	}

	for (i = 0; i < n; ++i){
		printf("No. %d's score\n", score[i]);
	}
	system("pause");
}

13、二维矩阵实现矩阵装置

/* 用二维数组实现矩阵的转置 */
#include <stdio.h>
#include <stdlib.h>
#define ROW 3
#define COL 4

void main()
{	
	int matrixA[ROW][COL], matrixB[COL][ROW];	/* 创建二维数组 */
	int i, j;

	printf("Enter elements of the matrixA,");
	printf("%d*%d:\n", ROW, COL);

	/* 手动输入矩阵 */
	for (i = 0; i<ROW; i++)
	{
		for (j = 0; j<COL; j++)
		{
			scanf("%d", &matrixA[i][j]);
		}
	}

	/* 将矩阵转置 */ 
	for (i = 0; i<ROW; i++)
	{
		for (j = 0; j<COL; j++)
		{
			matrixB[j][i] = matrixA[i][j];
		}
	}

	printf("MatrixB,");
	printf("%d*%d:\n", COL, ROW);
	for (i = 0; i<COL; i++)
	{
		for (j = 0; j<ROW; j++)
		{
			printf("%8d", matrixB[i][j]);
		}
		printf("\n");
	}

	getchar();
}

14、求解二维数组的最大最小元素

#include<stdio.h>
#include<stdlib.h> 
#define MAXN 20
int a[MAXN][MAXN];


void main()
{
	int min, max;	/* 存储最大值、最小值 */
	int row, col, n;

	printf("Please input the order of the matrix:");/* 输入方阵的阶次 */
	scanf("%d", &n);

	/* 输入矩阵 */
	printf("Please input the elements of the matrix,\n from a[0][0] to a[%d][%d]:", n - 1, n - 1);
	for (row = 0; row<n; row++)
		for (col = 0; col<n; col++)
			scanf("%d", &a[row][col]);

	/* 查找最大值 */
	for (min = a[0][0], row = 0; row<n; row++)
	{
		/* 从每行选出最大数 */
		for (max = a[row][0], col = 1; col<n; col++)/*从row行选出最大数 */
		if (max<a[row][col])
			max = a[row][col];
		if (min>max)/* 保存至row行的最小数 */
			min = max;
	}
	printf("The minimum of maximum number is %d\n", min);

	/* 查找最小值 */
	for (max = a[0][0], row = 0; row<n; row++)
	{
		/* 每行选出最小数 */
		for (min = a[row][0], col = 1; col<n; col++)/* 从row行选出最小数 */
		if (min>a[row][col])
			min = a[row][col];
		if (max<min)/*保存至row行的最大数 */
			max = min;
	}
	printf("The maximum of minimum numbers is %d\n", max);

	system("pause");
}

15、利用数组求前n个质数

#include<stdio.h>
#include<stdlib.h>

#define N 50
void main()
{
	int primes[N];
	int pc, m, k;

	printf("The first %d prime numbers are:\n", N);
	primes[0] = 2;		/*2是第一个质数*/
	pc = 1;				/*表示质数个数,已有第一个质数*/
	m = 3;				/*被测试的数从3开始*/
	while (pc<N)
	{
		/*调整m使它为下一个质数*/
		k = 0;
		while (primes[k] * primes[k] <= m){
			if (m%primes[k] == 0)
			{				/*m是合数*/
				m += 2;		/*让m取下一个奇数*/
				k = 1;		/*不必用primes[0]=2去测试m,所以k从一开始*/
			}
			else
				k++;			/*继续用下一个质数去测试*/
		}
		primes[pc++] = m;
		m += 2;				/*除2外,其余质数均是奇数*/
	}

	/*输出primes[0]至primes[pc-1]*/
	for (k = 0; k<pc; k++)
		printf("%4d", primes[k]);
	printf("\n\n Press any key to quit...\n ");
	system("pause");
}

16、万年历

#include <stdio.h>
#include <stdlib.h>

long int f(int year, int month)
{/*f(年,月)=年-1,如月<3;否则,f(年,月)=年*/
	if (month<3) return year - 1;
	else return year;
}

long int g(int month)
{/*g(月)=月+13,如月<3;否则,g(月)=月+1*/
	if (month<3) return month + 13;
	else return month + 1;
}

long int n(int year, int month, int day)
{
	/*N=1461*f(年、月)/4+153*g(月)/5+日*/
	return 1461L * f(year, month) / 4 + 153L * g(month) / 5 + day;
}

int w(int year, int month, int day)
{
	/*w=(N-621049)%7(0<=w<7)*/
	return(int)((n(year, month, day) % 7 - 621049L % 7 + 7) % 7);
}

int date[12][6][7] = {0};

/* 每个月份的最后一天日期 */
int day_tbl[][12] = { { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 },
{ 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } };


void main()
{
	int sw, leap, i, j, k, wd, day;
	int year; 
	char title[] = "SUN MON TUE WED THU FRI SAT";

	printf("Please input the year whose calendar you want to know: ");/*输入年*/
	scanf("%d%*c", &year);	/*输入年份值和掠过值后的回车*/

	/* 判闰年 */
	sw = w(year, 1, 1);			// 判断该年的年初第一天是星期几
	leap = year % 4 == 0 && year % 100 || year % 400 == 0;

	/* 一年十二个月,将第i+1月的日期填入日期表 */
	for (i = 0; i<12; i++)
		for (wd = 0, day = 1; day <= day_tbl[leap][i]; day++)
		{	
			date[i][wd][sw] = day;
			sw = ++sw % 7;				/* 每星期七天,以0至6计数 */
			if (sw == 0) wd++;			/* 日期表每七天一行,星期天开始新的一行 */
		}
	
	printf("\n|==================The Calendar of Year %d =====================|\n|", year);
	for (i = 0; i<6; i++)
	{/* 先测算第i+1月和第i+7月的最大星期数 */
		for (wd = 0, k = 0; k<7; k++)/* 日期表的第六行有日期,则wd!=0 */
			wd += date[i][5][k] + date[i + 6][5][k];
		wd = wd ? 6 : 5;
		printf("%2d  %s  %2d  %s |\n|", i + 1, title, i + 7, title);
		for (j = 0; j<wd; j++)
		{
			printf("   ");/* 输出四个空白符 */

			/* 左栏为第i+1月,右栏为第i+7月 */
			for (k = 0; k<7; k++)
				if (date[i][j][k])
					printf("%4d", date[i][j][k]);
				else printf("    ");

			printf("     ");/* 输出十个空白符 */

			for (k = 0; k<7; k++)
				if (date[i + 6][j][k])
					printf("%4d", date[i + 6][j][k]);
				else printf("    ");
			printf(" |\n|");
		}
	}
	puts("=================================================================|");
	system("pause");
}

在这里插入图片描述

17、数组排序

#include<stdio.h>
#include<stdlib.h>

void rest(int a[], int n)
{
	int i, low, high, tmp;

	for (i = 0, low = 0, high = n - 1; i <= high;)
	{
		if (a[i]>0)
		{
			/*a[i]与a[high]交换,随之high减1*/
			int tmp = a[i];
			a[i] = a[high];
			a[high--] = tmp;
		}
		else if (a[i] == 0)
			i++; /* 掠过该元素 */
		else
		{
			/*a[i]与a[low]交换,随之low增1, i增1*/
			tmp = a[i];
			a[i++] = a[low];
			a[low++] = tmp;
		}
	}
}
int s[] = { 8, 4, 0, -1, 6, 0, -5 };

void main()
{
	int i;
	printf("The arry before rest is:\n");
	for (i = 0; i<sizeof(s) / sizeof(s[0]); i++)
		printf("%4d", s[i]);

	/* 排序 */
	rest(s, sizeof(s) / sizeof(s[0]));

	printf("\nThe arry after rest is:\n");
	for (i = 0; i<sizeof(s) / sizeof(s[0]); i++)
		printf("%4d", s[i]);
	printf("\n");
	system("pause");
}

18、任意进制转换

#include<stdlib.h>
#include<stdio.h>

/* 函数trans将无符号整数n翻译成d(2<=d<=16)进制表示的字符串s */
#define M sizeof(unsigned int)*8
static char digits[] = "0123456789ABCDEF"; /* 十六进制数字的字符 */

/*
* @func:处理进制转换
* @param n:传入要转换的数值
* @param d:转化对应的进制
* @param s:传出参数
*/
int trans(unsigned n, int d, char s[])
{

	char buf[M + 1] = {0};
	int j, i = M;

	/* 不合理的进制,置s为空字符串 */
	if (d<2 || d>16)
	{
		s[0] = '\0';	
		return 0;	/* 不合理的进制,函数返回0 */
	}
	buf[i] = '\0';

	/*译出最低位,对应字符存入对应工作数组中*/
	do
	{
		buf[--i] = digits[n%d];	
		n /= d;
	} while (n);

	/* 将译出在工作数组中的字符串复制到s */
	for (j = 0; (s[j] = buf[i]) != '\0'; j++, i++);
	/* 其中控制条件可简写成s[j]=buf[i] */
	return j;
}


void main()
{
	unsigned int num = 253;
	int scale[] = { 2, 8, 10, 16, 1 };
	char ret[33];
	int i;

	for (i = 0; i<sizeof(scale) / sizeof(scale[0]); i++)
	{
		if (trans(num, scale[i], ret))
			printf("%5d = %s(%d)\n", num, ret, scale[i]);
		else
			printf("%5d => (%d) Error! \n", num, scale[i]);
	}
	system("pause");
}

19、回文数

#include<stdlib.h>
#include<stdio.h>


/* main函数用于测试circle函数 */
int num[] = { 232, 27, 851 };
int scale[] = { 2, 10, 16 };


/* 函数circle用于判断正整数n的d进制数表示形式是否是回文数 */
int circle(int n, int d)
{
	int s = 0, m = n;
	while(m)
	{
		s = s*d + m%d;
		m /= d;
	}

	return s==n;
}
 

void main()
{
	int i,j;
	for (i = 0; i < sizeof(num) / sizeof(num[0]); i++)
		for (j = 0; j < sizeof(scale) / sizeof(scale[0]); j++)
			if (circle(num[i], scale[j]))
				printf("%d -> (%d) is a Circle Number!\n", num[i], scale[j]);
			else
				printf("%d -> (%d) is not a Circle Number!\n", num[i], scale[j]);

	system("pause");
}

20、求数组前n项和

#include<stdlib.h>
#include<stdio.h>

int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 };


void main()
{
	int i, sum = 0;

	for (i = 0; i<sizeof(a) / sizeof(a[0]); i++)
		sum += a[i];
	printf("ret:%d\n", sum);
	system("pause");
}

21、求解钢材切割的最佳订单

#include <stdio.h>
#include <stdlib.h>
#define N 20
#define DELTA 2
int bestlen;
int bestsele[N];
int sele[N];
int n;
int orderlen[N];
int total;

void my_try()
{
	int i, len;
	for (len = i = 0; i<n; i++)	/* 求当前选中的用料量 */
		if (sele[i])
			len += orderlen[i] + DELTA;
	if (len - DELTA <= total)	/* 注意最后一段可能不需要切割 */
	{
		/* 找到一个更好的解 */
		if (bestlen < len)
		{
			bestlen = len;
			for (i = 0; i<n; i++)
				bestsele[i] = sele[i];
		}

		/* 对所有未选定单逐一作选中尝试循环 */
		for (i = 0; i<n; i++) 
			if (!sele[i])
			{
				sele[i] = 1;	/* 做选中尝试*/
				my_try();
				sele[i] = 0;
			}
	}
}


void main()
{
	int i;
	printf("Please enter total length of the steel: ");/* 输入钢材总长 */
	scanf("%d", &total);
	printf("Please enter number of order:");  /* 输入定单数 */
	scanf("%d", &n);
	printf("Please enter the orders:"); /* 输入各定单 */
	for (i = 0; i<n; i++)
		scanf("%d", &orderlen[i]);
	bestlen = 0;	/*最佳解用料的初值 */
	for (i = 0; i<n; i++)
		sele[i] = bestsele[i] = 0;	/*置当前选择和最佳选择初值 */
	my_try();	/* 调用函数求解 */
	for (i = 0; i<n; i++) /* 输出结果 */
		if (bestsele[i])
			printf("order %d length = %d\n", i + 1, orderlen[i]);
	system("pause");
}

22、通过指针比较整数大小

#include <stdio.h>
#include <stdlib.h>
void main()
{
	int x, y, z, t;	
	int *xp = &x,	/* 定义指针变量xp,并赋值为x的地址,使xp指向x */
		*yp = &y,	/* 定义指针变量yp,并赋值为y的地址,使yp指向y */
		*zp = &z;	/* 定义指针变量zp,并赋值为z的地址,使zp指向z */

	printf("Please input x,y,z: ");
	scanf("%d %d %d", xp, yp, zp);	/* 通过变量的指针,为变量输入值 */
	if (*xp>*yp)	/* 通过指向变量的指针引用变量的值 */
	{
		t = *xp;	/* 通过指向变量的指针引用变量的值 */
		*xp = *yp;/* 通过指向变量x的指针xp,引用变量x的值 */
		*yp = t;	/* 通过指向变量y的指针yp,引用变量y的值 */
	}
	if (*xp>*zp)	/* 通过指向变量的指针,引用变量的值 */
	{
		t = *xp;	/* 通过指向变量x的指针xp,引用变量x的值 */
		*xp = *zp;/* 通过指向变量x的指针xp,引用变量x的值 */
		*zp = t;	/* 通过指向变量z的指针zp,引用变量z的值 */
	}
	if (*yp>*zp)	/* 通过指向变量的指针,引用变量的值 */
	{
		t = *yp;	/* 通过指向变量的指针,引用变量的值 */
		*yp = *zp;/* 通过指向变量y的指针yp,引用变量y的值 */
		*zp = t;/* 通过指向变量z的指针zp,引用变量z的值 */
	}

	printf("x = %d\ty = %d\tz = %d\n", x, y, z);

	system("pause");
}

23、指向数组的指针

#include <stdio.h>
#include <stdlib.h>

int a[] = { 1, 2, 3, 4, 5 };

#define N sizeof a/sizeof a[0]

void main()
{
	int j, *p; 

	/* 数组名和下标顺序访问数组的元素 */
	for (j = 0; j<N; j++)
		printf("a[%d]\t= %d\t", j, a[j]);
	printf("\n");

	/* 让指针顺序指向数组的各元素,遍历数组 */
	for (p = a; p<a + N; p++)
		printf("*p\t= %d\t", *p);
	printf("\n");

	/* 指针与游标变量结合,改变游标变量遍历数组 */
	for (p = a, j = 0; p + j<a + N; j++)
		printf("*(p+%d)\t= %d\t", j, *(p + j));
	printf("\n");

	/* 指针与游标变量结合,用指针和下标遍历数组 */
	for (p = a + N - 1, j = N - 1; j >= 0; j--)
		printf("p[-%d]\t= %d\t", j, p[-j]);

	system("pause");
}

24、寻找指定元素的指针

#include <stdio.h>
#include <stdlib.h>

#define MAX 20


/*
* @param apt:已知数表的首元指针;
* @param n:数表中元素个数;
* @param key:要寻找的值;
* return:返回元素下标
*/
int search(int *apt, int n, int key)
{
	int *p;
	for (p = apt; p<apt + n; p++)
	if (*p == key)
		return p - apt;
	return -1;
}

/*
* @param apt:已知数表的首元指针;
* @param n:数表中元素个数;
* @param key:要寻找的值;
* return: 返回元素指针
*/
int *find(int *apt, int n, int key)
{
	int *p;
	for (p = apt; p<apt + n; p++)
	if (*p == key)
		return p;
	return NULL;
}

int a[] = { 90, 80, 70, 60, 50, 40, 30, 20, 10, 9, 8, 7, 6, 5, 42, 40, 50, 1, 2, 3 };
void main()
{
	int i, key;
	printf("The elements of array a is:\n");
	for (i = 0; i<sizeof(a) / sizeof(a[0]); i++)
		printf(" %d", a[i]);
	printf("\nThe address of a[0] is: %d.\n", &a[0]);	// 打印元素首地址

	/* 输入要查找的值 */
	printf("Please input the key number you want to search: ");
	scanf("%d", &key);

	i = search(a, sizeof(a) / sizeof(a[0]), key);
	printf("The label number of the key number %d in the array is: %d.\n", key, i);
	printf("The point value of the key number %d in the array is: %d.", key, find(a, sizeof(a) / sizeof(a[0]), key));

	system("pause");
}

25、寻找相同元素的指针

#include <stdio.h>
#include <stdlib.h>


/*
*@func:在已知两个从小到大有序的数表中寻找都出现的第一个元素的指针;
*@param pa: 传入数组1;
*@param pb: 传入数组2;
*@param an: 传入数组1长度;
*@param bn:传入数组2长度;
*/
int *search(int *pa,int *pb,int an,int bn)
{
	int *ca,*cb;

	ca = pa; cb = pb;	/* 为ca、cb设定初值 */
	while(ca < pa+an && cb< pb+bn )
	{
	/* 在两个数表中找下一个相等的元素 */
		if(*ca < *cb)		/* 数表1的当前元素<数表2的当前元素 */
		    ca++;			/* 调整数表1的当前元素指针 */
		else if(*ca>*cb)	/* 数表1的当前元素>数表2的当前元素 */
		    cb++;			/* 调整数表2的当前元素指针 */
		else				/* 数表1的当前元素==数表2的当前元素 */
			return ca;		/* 在前两个数表中找到相等元素, 则返回 */
	}
	return NULL;
}

void main( )
{
	int *vp,i;
	int a[]={1,3,5,7,9,13,15,27,29,37};
	int b[]={2,4,6,8,10,13,14,27,29,37};
	int len_a = sizeof(a) / sizeof(a[0]);
	int len_b = sizeof(b) / sizeof(b[0]);

	// 输出俩行数组
	puts("The elements of array a is:");
	for (i = 0; i < len_a; i++)
		printf(" %d",a[i]);
	puts("The elements of array b is:");
	for(i=0;i<sizeof(b)/sizeof(b[0]);i++)
		printf(" %d",b[i]);

	vp = search(a, b, len_a, len_b);

	if(vp) printf("\nThe first same number in both arrays is %d\n",*vp);
	else printf("Not found!\n");

	system("pause");

}

26、阿拉伯数字转化为罗马数字

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ROWS 4
#define COLS 4
int nums[ROWS][COLS] = { { 1000, 1000, 1000, 1000 },
						{ 900, 500, 400, 100 },
						{ 90, 50, 40, 10 },
						{ 9, 5, 4, 1 }
					};

char *roms[ROWS][COLS] = { { "m", "m", "m", "m" },
						{ "cm", "d", "cd", "c" },
						{ "xc", "l", "xl", "x" },
						{ "ix", "v", "iv", "i" } 
					};
/** 检查参数合理性 */
void checknum(int val)
{
	if (val<1 || val>9999)
	{
		printf("The number must be in range 1..9999.\n");
		exit(0);
	}
}

/** 将整数转换成罗马数字表示 */
void to_roman(int decimal, char roman[])
{
	int power, index;
	roman[0] = '\0';
	for (power = 0; power<ROWS; power++)
		for (index = 0; index<COLS; index++)
			while (decimal >= nums[power][index])
			{
				strcat(roman, roms[power][index]);
				decimal -= nums[power][index];
			}
}

void main()
{
	int low;
	char roman[25];

	printf("请输入第一个整数:");
	scanf("%d", &low);

	checknum(low);

	to_roman(low, roman);
	printf("%d\t%s\n", low, roman);


	system("pause");
}

27、字符替换

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define MAX 50

/* 将s中出现s1的字符串替换成s2 */
void rep(char *s, char *s1, char *s2)
{
	char *p;

	for (; *s; s++)							/* 顺序访问字符串s中的每个字符 */
	{
		for (p = s1; *p && *p != *s; p++);	/* 检查当前字符是否在字符串s1中出现 */
			if (*p)*s = *(p - s1 + s2);			/* 当前字符在字符串s1中出现,用字符串s2中的对应字符代替s中的字符 */
	}
}
void main()
{
	char s[MAX];	/*="ABCABC";*/
	char s1[MAX], s2[MAX];

	/* 交互从键盘获取字符串 */ 
	printf("Please input the string for s:");
	scanf("%s", s);
	printf("Please input the string for s1:");
	scanf("%s", s1);
	printf("Please input the string for s2:");
	scanf("%s", s2);

	rep(s, s1, s2);
	puts("The string of s after displace is:");
	printf("%s", s);

	system("pause");
}

28、从键盘读入实数

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define ERR 5
#define OK 6

int status;
double result, sig, scale;

/** 处理数的符号函数 */
int sign(int c)
{
	if (c == '-')/*若为负号,置负数标记*/
		sig = -sig;
	return sig;
}

/** 转换整数部分,转换一位整数位 */
int integer(int c)
{
	result = result*10.0 + c - '0';

	return result;
}

/** 转换小数部分,转换一位小数位 */
int decimal(int c)
{
	result += (c - '0')*scale;
	scale /= 10.0;

	return scale;
}


/** 状态表 */
int statbl[][4] = { { 1, 2, 3, ERR },	/*0*/
					{ ERR, 2, 3, ERR },	/*1*/
					{ OK, 2, 4, OK },	/*2*/
					{ ERR, 4, ERR, ERR },/*3*/
					{ OK, 4, OK, OK }   /*4*/
};										


/*转换函数表*/
int(*funtbl[][4])(int) = { { sign, integer, NULL, NULL },
						{ NULL, integer, NULL, NULL },
						{ NULL, integer, NULL, NULL },
						{ NULL, decimal, NULL, NULL },
						{ NULL, decimal, NULL, NULL }
					};

int readreal(double *dp)
{
	int c, ckind;
	sig = 1.0;
	result = 0.0;
	scale = 0.1;

	/* 跳过前导空白符 */
	while ((c = getchar()) == ' ' || c == '\n' || c == '\t');
	status = 0;									/* 置初始状态 */
	for (;;)
	{
		/* 分类当前字符 */
		if (c == '+' || c == '-') 
			ckind = 0;							/* 数的符号字符 */
		else if (c >= '0'&&c <= '9') 
			ckind = 1;							/* 数字符 */
		else if (c == '.') 
			ckind = 2;							/* 小数点 */
		else 
			ckind = 3;							/* 其它字符 */

		/* 字符转换 */
		if (funtbl[status][ckind])				/* 如有转换函数 */
			(*funtbl[status][ckind])(c);		/* 执行相应的函数 */
		status = statbl[status][ckind];			/* 设置新的状态 */
		if (status == ERR || status == OK) break;/* 结束:出错或成功 */
		c = getchar();
	}
	ungetc(c, stdin);							/* 归还数德结束符 */
	if (status == OK)
	{
		*dp = result *sig;						/* 读入数按指针参数赋给相应变量 */
		return 1;
	}
	return -1;				
}

void main()
{
	double x;
	printf("Please input real numbers (use nonreal char to end input): ");
	while (readreal(&x) == 1)
		printf("The real number you input is: %f ", x);

	system("pause");
}

29、字符行排版

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* 字符排版函数,将字符行内单字之间的空白字符平均分配插入到单字之间*/
#define N 80

void edit(char *s)
{
	int i, sp, w, inw, v, r;
	char buf[N], *str;
	for (inw = sp = w = i = 0; s[i]; i++)
	{
		/* 统计空白个数*/
		if (s[i] == ' ')
		{	
			sp++;
			inw = 0;	/* 置空白符状态*/
		}
		else if (!inw)
		{
			w++;		/* 统计单字个数*/
			inw = 1;	/* 置单字状态*/
		}
	}

	/* 单字数不超过1, 不排版 */
	if (w <= 1)
		return;	
	v = sp / (w - 1);	/* 每个间隔平均空白符 */
	r = sp % (w - 1);	/* 多余的空白符 */
	strcpy(buf, s);
	for (str = buf;;)
	{
		while (*str == ' ')str++;  /* 掠过空白符 */
		for (; *str&&*str != ' ';) /* 复制单字 */
			*s++ = *str++;b
		if (--w == 0)
			return;					/* 全部单字复制完毕,返回 */
		for (i = 0; i<v; i++)
			*s++ = ' ';				/* 插入间隔空白符 */
		if (r)
		{
			*s++ = ' ';				/* 插入一个多余空白符 */
			r--;
		}
	}
}
char buff[N];

void main()		
{
	printf("This is a typeset program!\nPlease input a character line:");
	gets(buff);
	edit(buff);
	printf("\nThe character line after typeset is:\n\n%s", buff);

	system("pause");
}

30、字符排列

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

/* 字符串的所有字符排列函数,用已知字符串s中的所有字符,生成由其中n个字符组成的所有字符排列 */
#define N 20
char w[N];
void perm(int n, char *s)
{
	char s1[N];
	int i;
	if (n<1)
		printf("%s\n", w); /* 一个排列生成输出 */
	else
	{
		strcpy(s1, s);	/* 保存本层次可使用的字符 */
		for (i = 0; *(s1 + i); i++)	/* 依次选本层次可用字符 */
		{
			*(w + n - 1) = *(s1 + i);/* 将选用字符填入正在生成的字符排列中 */
			*(s1 + i) = *s1;
			*s1 = *(w + n - 1);
			perm(n - 1, s1 + 1);	 /* 递归 */
		}
	}
}

void main()
{
	int n = 2;
	char s[N];
	w[n] = '\0';
	printf("This is a char permutation program!\nPlease input a string:");
	scanf("%s", s);
	printf("Please input the char number of permuted:");
	scanf("%d", &n);
	printf("The permuted chars are:");
	perm(n, s);

	system("pause");
}

31、判断字符串是否回文

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define MAX 50

int cycle(char *s)
{
	char *h, *t;

	/*
	* 使用俩个指针分别指向字符串数组的头部和尾部,判断俩个字符是否相等
	*/
	for (h = s, t = s + strlen(s) - 1; t>h; h++, t--)
	if (*h != *t) break;
	return t <= h;
}

void main()
{
	char s[MAX];

	while (1)
	{
		printf("Please input the string you want to judge (input ^ to quit):");
		scanf("%s", s);
		if (s[0] == '^') break;
		if (strlen(s) <= 2) continue;
		if (cycle(s))
			printf("%s是回文数\n", s);
		else
			printf("%s不是回文数\n", s);
	}

	system("pause");
}

32、通讯录的输入输出

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define ZIPLEN 10
#define PHONLEN 15

typedef struct addrbook
{
	char *name;			/*姓名*/
	char *address;		/*地址*/
	char zip[ZIPLEN];	/*邮政编码*/
	char phone[PHONLEN];/*电话号码*/
}addrBook;

int readaddr(addrBook *);
void writeaddr(addrBook*);


void main()
{
	addrBook p[100];
	int i, j;
	for (i = 0; readaddr(p + i); i++);
	for (j = 0; j<i; j++) writeaddr(p + j);

	system("pause");
}

/* 函数readaddr用于输入一个通信录函数 */
int readaddr(addrBook *dpt)
{
	int len;
	char buf[120];							/* 输入字符串的缓冲区 */

	/* 输入姓名 */
	printf("Please input the Name:");	
	if (scanf("%s", buf) == 1)
	{
		len = strlen(buf);
		dpt->name = (char *)malloc(len + 1);/* 申请存贮姓名的空间 */
		strcpy(dpt->name, buf);
	}
	else return 0;						/*Ctrl+Z结束输入*/

	/* 输入地址 */
	printf("Please input the Address:");
	if (scanf("%s", buf) == 1)
	{
		len = strlen(buf);
		dpt->address = (char *)malloc(len + 1);/*申请存贮地址的空间*/
		strcpy(dpt->address, buf);
	}
	else
	{
		free(dpt->name);/* 释放存贮姓名的空间 */
		return 0;
	}

	/* 输入邮编 */
	printf("Please input the Zip code:");
	if (scanf("%s", buf) == 1)
		strncpy(dpt->zip, buf, ZIPLEN - 1);
	else
	{
		free(dpt->name);/*释放存贮姓名的空间*/
		free(dpt->address);/*释放存贮地址的空间*/
		return 0;
	}

	/* 输入电话号码 */
	printf("Please input the Phone number:");
	if (scanf("%s", buf) == 1)
		strncpy(dpt->phone, buf, PHONLEN - 1);
	else
	{
		free(dpt->name);
		free(dpt->address);
		return 0;
	}
	return 1;
}

/* 函数writeaddr用于输出通讯录 */
void writeaddr(addrBook *dpt)
{
	printf("Name	:   %s\n", dpt->name);		/*输出姓名*/
	printf("Address	:   %s\n", dpt->address);	/*输出地址*/
	printf("Zip	:   %s\n", dpt->zip);			/*输出邮编*/
	printf("Phone	:   %s\n\n", dpt->phone);	/*输出电话号码*/
}

33、扑克牌的结构表示

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

enum suits{ CLUBS=0, DIAMONDS, HEARTS, SPADES } suit;
typedef struct card
{
	enum suits suit;
	char value[3];
}Card;

Card deck[52];
char cardval[][3] = { "A", "2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K" };
char suitsname[][9] = { "CLUBS", "DIAMONDS", "HEARTS", "SPADES" };

void main()
{
	int i, j, k;

	for (i = 0; i <= 12; i++)
	for (k = CLUBS; k <= SPADES; k++)
	{
		j = i * 4 + k;
		deck[j].suit = (enum suits)k;
		strcpy(deck[j].value, cardval[i]);
	}
	for (j = 0; j<52; j++)
		printf("(%s%3s)%c", suitsname[deck[j].suit], deck[j].value, j % 4 == 3 ? '\n' : '\t');

	system("pause");
}

34、用“结构”统计学生成绩

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


#define N 200
#define SCORES 5
#define NUMLEN 10

typedef struct std_type{
	char no[NUMLEN];		/* 学号 */
	char *name;				/* 名字符串指针 */
	int scores[SCORES];		/* 五门功课的成绩 */
}stdType;

stdType students[N];
int order[N];
int total[N];

/* [函数]输入一个学生信息函数 */
int readastu(stdType *spt)
{
	int len, j;
	char buf[120];/*输入字符串的缓冲区*/

	/*输入学号*/
	printf("Number   :   ");
	if (scanf("%s", buf) == 1)
		strncpy(spt->no, buf, NUMLEN - 1);
	else
		return 0;/*Ctrl+Z结束输入*/

	/*输入姓名*/
	printf("Name   :   ");
	if (scanf("%s", buf) == 1)
	{
		len = strlen(buf);
		spt->name = (char *)malloc(len + 1);/*申请存贮姓名的空间*/
		strcpy(spt->name, buf);
	}
	else return 0;/*Ctrl+Z结束输入*/

	/*输入成绩*/
	printf("Scores   :   ");
	for (j = 0; j<SCORES; j++)
	if (scanf("%d", spt->scores + j) != 1)
		break;
	if (j == 0)/*一个成绩也未输入*/
	{
		free(spt->name);/* 释放存贮姓名的空间 */
		return 0;
	}
	for (; j<SCORES; j++)/* 少数未输入的成绩用0分代之 */
		spt->scores[j] = 0;
	return 1;
}

/* [函数]输出一个学生信息的函数 */
void writeastu(stdType *spt)
{
	int i;

	printf("Number   :   %s\n", spt->no);/*输出学号*/
	printf("Name     :   %s\n", spt->name);/*输出姓名*/
	printf("Scores   :   ");/*输出成绩*/
	for (i = 0; i<SCORES; i++)
		printf("%4d", spt->scores[i]);
	printf("\n\n");
}

void main()
{
	int n, i, j, t;

	for (n = 0; readastu(students + n); n++);
	/*采用冒泡法对学生信息数组排序*/
	for (i = 0; i<n; i++)
	{
		order[i] = i;/*预置第i个输入的学生*/
		for (t = 0, j = 0; j<SCORES; j++)/*求第i个学生的总分*/
			t += students[i].scores[j];
		total[i] = t;
	}
	/*冒泡排序*/
	for (i = 0; i < n - 1; i++)/* 共扫视n-1遍 */
	for (j = 0; j < n - 1 - i; j++)
	if (total[order[j]]<total[order[j + 1]])
	{/*交换名次*/
		t = order[j];
		order[j] = order[j + 1];
		order[j + 1] = t;
	}
	for (j = 0; j<n; j++)/*输出*/
		writeastu(students + order[j]);
	system("pause");
}

35、报数游戏

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

struct ele{
	int no;
	struct ele *next;
};

void main()
{
	int n, m, i;
	struct ele *h, *u, *p;

	printf("Please input n&m:");
	scanf("%d %d", &n, &m);		/*输入n和m*/
	h = u = (struct ele *)malloc(sizeof(struct ele));/*形成首表元*/
	h->no = 1;
	for (i = 2; i <= n; i++)	/*形成其余的n-1个表元*/
	{
		u->next = (struct ele *)malloc(sizeof(struct ele));
		u = u->next;
		u->no = i;				/*第i个表元置编号i*/
	}
	u->next = h;				/*末表元后继首表元,形成环*/
	printf("The numbers of who will quit the cycle in turn are:");
	while (n)
	{
		for (i = 1; i<m; i++)		/*掠过m-1个表元*/
			u = u->next;
		p = u->next;				/*p指向第m个表元*/
		u->next = p->next;			/*第m个表元从环中脱钩*/
		printf("%4d", p->no);
		free(p);					/*释放第m个表元占用的空间*/
		n--;
	}
	system("pause");
}

36、模拟家族关系

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include <stdio.h>
#define CHILDREN 5

typedef struct person{
	char *name;							/*名字符串指针*/
	char sex;							/*性别:男用字符'M';女用字符'F'*/
	struct person *father;				/*指向父亲*/
	struct person *mother;				/*指向母亲*/
	struct person *mate;				/*指向配偶*/
	struct person *children[CHILDREN];	/*指向子女*/
}Person;

/* 增加新人 */
Person *add_person(char *name, char sex)
{
	Person *p;
	int index;

	p = (Person *)malloc(sizeof(Person));
	p->name = (char *)malloc(strlen(name) + 1);
	strcpy(p->name, name);
	p->sex = sex;
	p->father = NULL;
	p->mother = NULL;
	p->mate = NULL;
	for (index = 0; index<CHILDREN; index++)
		p->children[index] = NULL;
	return p;
}

/* 建立父-子关系 */
void father_child(Person *father, Person *child)
{
	int index;

	for (index = 0; index < CHILDREN - 1; index++)	/*  寻找一个空缺的子女指针 */
		if (father->children[index] == NULL)		/*若没有空缺,则填在最后 */
			break;
	father->children[index] = child;				/* 建立父-子关系 */
	child->father = father;
}
/* 建立母-子关系 */
void mother_child(Person *mother, Person *child)
{
	int index;
	for (index = 0; index<CHILDREN - 1; index++)	/*寻找一个空缺的子女指针*/
		if (mother->children[index] == NULL)		/*若没有空缺,则填在最后*/
			break;
	mother->children[index] = child;				/*建立母-子关系*/
}

/* 建立配偶关系 */
void mate(Person *h, Person *w)
{

	h->mate = w;	/*建立配偶关系*/
	w->mate = h;
}

/* 检查两人是否是堂兄妹 */
int brothersinlaw(Person *p1, Person *p2)
{
	Person *f1, *f2;

	if (p1 == NULL || p2 == NULL || p1 == p2) return 0;
	if (p1->sex == p2->sex) return 0;			/* 根据性别不可能是堂兄妹 */
	f1 = p1->father;
	f2 = p2->father;
	if (f1 != NULL && f1 == f2) return 0;		/* 是兄妹,不是堂兄妹 */
	while (f1 != NULL&&f2 != NULL&&f1 != f2)	/* 考虑远房情况 */
	{
		f1 = f1->father;
		f2 = f2->father;
		if (f1 != NULL&&f2 != NULL&&f1 == f2) return 1;
	}
	return 0;
}

/* 用于输出人物p的姓名,性别和各种关系 */
void print_relate(Person *p)
{
	int index, i;
	if (p->name == NULL)
		return;
	if (p->sex == 'M')
		printf("%s is male.", p->name);
	else
		printf("%s is female.", p->name);
	if (p->father != NULL)
		printf("%s's father is %s.", p->name, p->father->name);
	if (p->mother != NULL)
		printf("%s's mother is %s.", p->name, p->mother->name);
	printf("\n");
	if (p->mate != NULL)
	if (p->sex == 'M')
		printf("His wife is %s.", p->mate->name);
	else
		printf("Her husband is %s.", p->mate->name);
	if (p->children != NULL)
	{
		for (index = 0; index<CHILDREN - 1; index++)/*寻找一个空缺的子女指针*/
		if (p->children[index] == NULL)/*若没有空缺,index为子女个数 */
			break;
		if (index>0)
			printf(" Children are:");
		for (i = 0; i<index; i++)
			printf(" %s", p->children[i]->name);
	}
	printf("\n");

}
void main()
{
	char *name[8] = { "John", "Kate", "Maggie", "Herry", "Jason", "Peter", "Marry", "Jenny" };
	char male = 'M', female = 'F';
	Person *pGrandfather, *pFather1, *pFather2, *pMother1, *pMother2, *pSon, *pDaughter, *pCousin;
	// 添加任务信息
	pGrandfather = add_person(name[0], male);
	pFather1 = add_person(name[3], male);
	pFather2 = add_person(name[4], male);
	pMother1 = add_person(name[1], female);
	pMother2 = add_person(name[2], female);
	pSon = add_person(name[5], male);
	pDaughter = add_person(name[6], female);
	pCousin = add_person(name[7], female);

	// 父子关系
	father_child(pGrandfather, pFather1);
	father_child(pGrandfather, pFather2);
	father_child(pFather1, pSon);
	father_child(pFather1, pDaughter);
	father_child(pFather2, pCousin);
	
	// 配偶关系
	mate(pFather1, pMother1);
	mate(pFather2, pMother2);

	// 母子关系
	mother_child(pMother1, pSon);
	mother_child(pMother1, pDaughter);
	mother_child(pMother2, pCousin);

	/* 输出各种关系 */
	print_relate(pGrandfather);
	print_relate(pFather1);
	print_relate(pFather2);
	print_relate(pMother1);
	print_relate(pMother2);
	print_relate(pSon);
	print_relate(pDaughter);
	print_relate(pCousin);


	if (!brothersinlaw(pDaughter, pCousin))
		printf("%s and %s are not brothers (sisters) in law.\n", pDaughter->name, pCousin->name);
	else
		printf("%s and %s are brothers (sisters) in law.\n", pDaughter->name, pCousin->name);
	if (!brothersinlaw(pSon, pCousin))
		printf("%s and %s are not brothers (sisters) in law.\n", pSon->name, pCousin->name);
	else
		printf("%s and %s are brothers (sisters) in law.\n", pSon->name, pCousin->name);
	if (!brothersinlaw(pSon, pDaughter))
		printf("%s and %s are not brothers (sisters) in law.\n", pSon->name, pDaughter->name);
	else
		printf("%s and %s are brothers (sisters) in law.\n", pSon->name, pDaughter->name);

	system("pause");
}

37、统计文件的字符数

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

void main()
{
	char fname[80];	/*存贮文件名*/
	char buf[1024];
	FILE *rfp;
	long count;		/*文件字符计数器*/

	printf("Please input the file's name:\n");
	scanf("%s", fname);
	if ((rfp = fopen(fname, "r")) == NULL)
	{
		printf("Can't open file %s.\n", fname);
		exit(1);
	}
	count = 0;
	while (fgets(buf, 1024, rfp) != NULL)
		count += strlen(buf);
	fclose(rfp);
	printf("There are %ld characters in file %s.\n", count, fname);

	system("pause");
}

38、同时显示两个文件的内容

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#define PAGELINE   20
#define PAGESPLINE 2
#define TXTWIDTH   30
#define TXTGAP     10

void linecount()/*完成对输出行的计数和一页满后,输出空行*/
{
	static int pline = 0;
	int i;

	if (++pline == PAGELINE)
	{
		for (i = 0; i<PAGESPLINE; i++)/*输出一页后的空行*/
			printf("\n");
		pline = 0;
	}
}

int readline(FILE *fpt)/*完成从指定的文件中读出一行多至30个字符并输出*/
{
	int c, cpos = 0;

	while ((c = fgetc(fpt)) != '\n')
	{
		if (feof(fpt))
			break;/*文件结束推出循环*/
		printf("%c", c);
		cpos++;
		if (cpos >= TXTWIDTH)
			break;
	}
	return cpos;/*返回读入并输出的字符数*/
}

void main()
{
	FILE *fpt1, *fpt2;
	char fname1[20], fname2[20];			/*存贮文件名*/
	int fill1, fill2;			/*分别记录两个文件当前行读入并输出的字符数*/

	printf("Enter file 1 name:");
	scanf("%s", fname1);
	fpt1 = fopen(fname1, "r");	/*打开文件1*/
	if (fpt1 == NULL)
	{
		printf("Can't open file %s.\n", fname1);
		exit(1);
	}

	printf("Enter file 2 name:");
	fpt2 = fopen(fname2, "r");	/*打开文件2*/
	if (fpt2 == NULL)
	{
		fclose(fpt1);
		exit(2);
	}

	while (!feof(fpt1) || !feof(fpt2))	/* 在有文件还未结束时循环 */
	{
		fill1 = fill2 = 0;
		if (!feof(fpt1)) fill1 = readline(fpt1);/* 在文件未结束时读文件 */
		printf("%*c", TXTWIDTH - fill1 + TXTGAP, ' ');
		if (!feof(fpt2)) fill2 = readline(fpt2);/* 在文件未结束时读文件 */
		printf("%*c%2d\n", TXTWIDTH - fill2 + 4, ' ', fill1 + fill2);
		linecount();					/* 调用行计数函数 */
	}
	system("pause");
}

39、简单的文本编辑器

#include<stdio.h>
#include<stdlib.h>
#include<string.h>


/*
	根据命令对文件进行编辑,创建,保存,删除,退出,追加等操作
*/

typedef enum fileoper
{
	EDIT = 'i',
	CREAT = 'c',
	SAVE = 's',
	DEL = 'd',
	APPEND = 'a',
	QUIT = 'q'
}fileOper;

/*
* @func:编辑文本,需要先打开/创建文件
*/
void edit_text(FILE *fp){
	int i = 0;
	char buf[1024] = { 0 };
	char *content[20];
	while (gets(buf) != NULL || buf != "\n")
	{
		if (buf == "\n") content;
		if (buf[0] == '^') break;
		content[i] = (char *)malloc(sizeof(char)* strlen(buf)+1);
		strcpy(content[i], buf);
		i++;
	}
	for (int j = 0; j < i; ++j){
		fputs(content[j], fp);
		free(content[j]);
		content[j] = NULL;
	}
	
	fclose(fp);
}

/** 创建文件 */
FILE *create_file(const char *filename){
	FILE *fp = fopen(filename, "w");
	if (fp != NULL){
		printf("文件创建成功...\n");
		return fp;
	}
	return NULL;
}

void del_file(const char *filename){
	if (remove(filename) == 0)
		printf("%s删除成功...\n", filename);
	else
		printf("%s文件删除失败...\n", filename);
}

void quit_edit(FILE *fp){
	if (fclose(fp) == 0)
		printf("文件关闭成功...\n");

}

void append_text(const char *filename, FILE *fp){
	FILE *fp_append = freopen(filename, "a+", fp);
	fseek(fp_append, 0, SEEK_END);  // 将文件指针设置到文件末尾
	edit_text(fp_append);
}

void main()
{
	char ch;
	char filename[20];
	FILE *fp = NULL;
	printf("--正在使用文件操作系统\n");
	printf("-------i. 编辑-------\n");
	printf("-------c. 创建-------\n");
	printf("-------s. 保存-------\n");
	printf("-------d. 删除-------\n");
	printf("-------a. 追加-------\n");
	printf("-------q. 退出-------\n");
	while (1)
	{
		printf("--请输入文件操作命令:");

		ch = getchar();
		fflush(stdin);

		switch (ch){
		case EDIT:
			if (fp == NULL){
				printf("请先创建文件/打开文件在进行相应操作...");
				break;
			}
			edit_text(fp);
			break;
		case CREAT:
			printf("请输入创建的文件名:");
			if (scanf("%s", filename) == 1)
				
				fp = create_file(filename);
			else
				printf("ERROR:输入有误...");
			fflush(stdin);
			break;
		case APPEND:
			printf("请输入追加的文件名:");
			if (scanf("%s", filename) != 1){
				printf("ERROR:输入有误...");
				break;
			}
			if (fp == NULL){
				break;
			}
			append_text(filename, fp);
			fflush(stdin);
			break;
		case DEL:
			printf("请输入要删除的文件名:");
			if (scanf("%s", filename) == 1)
				del_file(filename);
			else
				printf("ERROR:输入有误...");
			break;
		case QUIT:
			if (fp == NULL){
				printf("请先创建文件/打开文件在进行相应操作...");
				break;
			}
			quit_edit(fp);
			break;
		default:
			;
		}
	}

	system("pause");
}

40、文件的字数统计程序

#include<stdio.h>
#include<stdlib.h>
/*
该程序实现统计一个或多个文件的行数、字数和字符数。
一个行由一个换行符限定,一个字由空格分隔(包括空白符、制表符和换行符),
字符是指文件中的所有字符。要求程序另设三个任选的参数,
让用户指定他所要的统计。它们是:
1 统计文件行数
w 统计文件字数
c 统计文件字符数
若用户未指定任选的参数,则表示三个统计都要。
运行本程序时的参数按一下格式给出:
-l -w -c 文件 文件 ... 文件
其中,前三个任选参数l、w、c的出现与否和出现顺序任意,
或任意组合在一起出现,如:-lwc,-cwl,-lw,-wl,-lc,-cl,-cw等。
*/

void main(int argc, char **argv)
{
	FILE *fp;
	int lflg, wflg, cflg; /* l, w, c三个标志 */
	int inline_, inword; /* 行内和字内标志 */
	int ccount, wcount, lcount; /* 字符,字,行 计数器 */
	int c;
	char *s;
	lflg = wflg = cflg = 0;
	if (argc<2)
	{
		printf("To run this program, usage: program -l -w -c file1 file2 ... filen \n");
		exit(0);
	}
	while (--argc >= 1 && (*++argv)[0] == '-')
	{
		for (s = argv[0] + 1; *s != '\0'; s++)
		{
			switch (*s)
			{
			case 'l':
				lflg = 1;
				break;
			case 'w':
				wflg = 1;
				break;
			case 'c':
				cflg = 1;
				break;
			default:
				puts("To run this program, usage: program -l -w -c file1 file2 ... filen");
				exit(0);
			}
		}
	}
	if (lflg == 0 && wflg == 0 && cflg == 0)
		lflg = wflg = cflg = 1;
	lcount = wcount = ccount = 0;
	while (--argc >= 0)
	{
		if ((fp = fopen(*argv++, "r")) == NULL)	/* 以只读方式打开文件 */
		{
			fprintf(stderr, "Can't open %s.\n", *argv);
			continue;
		}
		inword = inline_ = 0;
		while ((c = fgetc(fp)) != EOF)
		{
			if (cflg)
				ccount++;
			if (wflg)
			if (c == '\n' || c == ' ' || c == '\t')
				inword = 0;
			else if (inword == 0)
			{
				wcount++;
				inword = 1;
			}
			if (lflg)
			if (c == '\n')
				inline_ = 0;
			else if (inline_ == 0)
			{
				lcount++;
				inline_ = 1;
			}
		}
		fclose(fp);	/* 关闭文件 */
	}
	if (lflg)
		printf(" Lines =         %d\n", lcount);
	if (wflg)
		printf(" Words =         %d\n", wcount);
	if (cflg)
		printf(" Characters =    %d\n", ccount);
}

41、学生成绩管理程序

#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<string.h>
#include<stdio.h>


/*
学生成绩管理程序
编制一个统计学生考试分数的管理程序。
设学生成绩已以一个学生一个记录的形式存储在文件中,
每位学生记录包含的信息有:姓名,学号和各门功课的成绩。
程序具有以下几项功能:求出各门课程的总分,平均分,按姓名,
按学号寻找其记录并显示,浏览全部学生成绩和按总分由高到低显示学生信息等。
*/
#define	SWN		3	/* 课程数 */
#define NAMELEN		20	/* 姓名最大字符数 */
#define CODELEN		10	/* 学号最大字符数 */
#define FNAMELEN	80	/* 文件名最大字符数 */
#define BUFLEN		80	/* 缓冲区最大字符数 */

/* 课程名称表 */
char schoolwork[SWN][NAMELEN + 1] = { "Chinese", "Mathematic", "English" };
struct record
{
	char	name[NAMELEN + 1];	/* 姓名 */
	char 	code[CODELEN + 1];	/* 学号 */
	int 	marks[SWN];			/* 各课程成绩 */
	int total;					/* 总分 */
}stu;

struct node
{
	char	name[NAMELEN + 1];	/* 姓名 */
	char 	code[CODELEN + 1];	/* 学号 */
	int 	marks[SWN];			/* 各课程成绩 */
	int 	total;				/* 总分 */
	struct	node *next;			/* 后续表元指针 */
}*head;							/* 链表首指针 */

int total[SWN];					/* 各课程总分 */
FILE *stfpt;					/* 文件指针 */
char stuf[FNAMELEN];			/* 文件名 */

/** 从指定文件读入一个记录, 使用fscanf读取,一次读取一行*/
int read_record(FILE *fpt, struct record *rpt)
{
	char buf[BUFLEN];
	int i;
	if (fscanf(fpt, "%s", buf) != 1)	// 读取姓名	
		return 0;						/* 文件结束 */ 
	strncpy(rpt->name, buf, NAMELEN);	
	fscanf(fpt, "%s", buf);				// 读取学号
	strncpy(rpt->code, buf, CODELEN);
	for (i = 0; i < SWN; i++)			// 读取成绩
		fscanf(fpt, "%d", &rpt->marks[i]);

	for (rpt->total = 0, i = 0; i<SWN; i++)
		rpt->total += rpt->marks[i];
	return 1;
}

/** 对指定文件写入一个记录 */
void write_record(FILE *fpt, struct record *rpt)
{
	int i;
	fprintf(fpt, "%s\n", rpt->name);
	fprintf(fpt, "%s\n", rpt->code);
	for (i = 0; i<SWN; i++)
		fprintf(fpt, "%d\n", rpt->marks[i]);
	return;
}

/** 显示学生记录 */
void displaystu(struct record *rpt)
{
	int i;
	printf("\nName   : %s\n", rpt->name);
	printf("Code   : %s\n", rpt->code);
	printf("Marks  :\n");
	for (i = 0; i<SWN; i++)
		printf("       %-15s : %4d\n", schoolwork[i], rpt->marks[i]);
	printf("Total  : %4d\n", rpt->total);
}

/** 计算各单科总分 */
int totalmark(char *fname)
{
	FILE *fp;
	struct record s;
	int count, i;
	if ((fp = fopen(fname, "r")) == NULL)
	{
		printf("Can't open file %s.\n", fname);
		return 0;
	}
	// 初始化为0
	for (i = 0; i<SWN; i++)
		total[i] = 0;
	count = 0;
	// 将各科成绩相加
	while (read_record(fp, &s) != 0)
	{
		for (i = 0; i<SWN; i++)
			total[i] += s.marks[i];
		count++;
	}
	fclose(fp);
	return count;	/* 返回记录数 */
}

/* 列表显示学生信息 */
void liststu(char *fname)
{
	FILE *fp;
	struct record s;
	if ((fp = fopen(fname, "r")) == NULL)
	{
		printf("Can't open file %s.\n", fname);
		return;
	}
	while (read_record(fp, &s) != 0)
	{
		displaystu(&s);
		printf("\n      Press ENTER to continue...\n");
		while (getchar() != '\n');
	}
	fclose(fp);
	return;
}

/* 构造链表 */
struct node *makelist(char *fname)
{
	FILE *fp;
	struct record s;
	struct node *p, *u, *v, *h;
	int i;
	if ((fp = fopen(fname, "r")) == NULL)
	{
		printf("Can't open file %s.\n", fname);
		return NULL;
	}
	h = NULL;
	p = (struct node *)malloc(sizeof(struct node));
	u = (struct node *)malloc(sizeof(struct node));
	while (read_record(fp, (struct record *)p) != 0)
	{
		v = h;
		while (v&&p->total <= v->total)
		{
			u = v;
			v = v->next;
		}
		if (v == h)
			h = p;
		else
			u->next = p;
		p->next = v;
		p = (struct node *)malloc(sizeof(struct node));
	}
	free(p);
	fclose(fp);
	return h;
}

/* 顺序显示链表各表元 */
void displaylist(struct node *h)
{
	while (h != NULL)
	{
		displaystu((struct record *)h);
		printf("\n      Press ENTER to continue...\n");
		while (getchar() != '\n');
		h = h->next;
	}
	return;
}
/* 按学生姓名查找学生记录 */
int retrievebyn(char *fname, char *key)
{
	FILE *fp;
	int c;
	struct record s;
	if ((fp = fopen(fname, "r")) == NULL)
	{
		printf("Can't open file %s.\n", fname);
		return 0;
	}
	c = 0;
	while (read_record(fp, &s) != 0)
	{
		if (strcmp(s.name, key) == 0)
		{
			displaystu(&s);
			c++;
		}
	}
	fclose(fp);
	if (c == 0)
		printf("The student %s is not in the file %s.\n", key, fname);
	return 1;
}

/* 按学生学号查找学生记录 */
int retrievebyc(char *fname, char *key)
{
	FILE *fp;
	int c;
	struct record s;
	if ((fp = fopen(fname, "r")) == NULL)
	{
		printf("Can't open file %s.\n", fname);
		return 0;
	}
	c = 0;
	while (read_record(fp, &s) != 0)
	{
		if (strcmp(s.code, key) == 0)
		{
			displaystu(&s);
			c++;
			break;
		}
	}
	fclose(fp);
	if (c == 0)
		printf("The student %s is not in the file %s.\n", key, fname);
	return 1;
}

void main()
{
	int i, j, n;
	char c;
	char buf[BUFLEN];
	FILE *fp;
	struct record s;
	printf("Please input the students marks record file's name: ");
	scanf("%s", stuf);
	/* 判断该学生的档案是否存在 */ 
	if ((fp = fopen(stuf, "r")) == NULL)
	{
		printf("The file %s doesn't exit, do you want to creat it? (Y/N) ", stuf);
		getchar();
		c = getchar();
		if (c == 'Y' || c == 'y')
		{
			fp = fopen(stuf, "w");
			printf("Please input the record number you want to write to the file: ");
			scanf("%d", &n);
			/* 循环将学生信息录入 */
			for (i = 0; i<n; i++)
			{
				printf("Input the student's name: ");
				scanf("%s", &s.name);
				printf("Input the student's code: ");
				scanf("%s", &s.code);
				for (j = 0; j<SWN; j++)
				{
					printf("Input the %s mark: ", schoolwork[j]);
					scanf("%d", &s.marks[j]);
				}
				write_record(fp, &s);	// 写入文件
			}
			fclose(fp);
		}
	}
	fclose(fp);
	getchar();
	puts("---------------------------------------------------");
	puts("Now you can input a command to manage the records.");
	puts("m : mean of the marks.");
	puts("t : total of the marks.");
	puts("n : search record by student's name.");
	puts("c : search record by student's code.");
	puts("l : list all the records.");
	puts("s : sort and list the records by the total.");
	puts("q : quit!");
	while (1)
	{
		printf("Please enter your choice:");
		scanf(" %c", &c);		/* 输入选择命令 */
		if (c == 'q' || c == 'Q')
		{
			puts("\n Thank you for your using.");
			break;		/* q,结束程序运行 */
		}
		switch (c)
		{

		/* 计算平均分 */
		case 'm': 
		case 'M':
			if ((n = totalmark(stuf)) == 0)
			{
				puts("Error!");
				break;
			}
			printf("\n");
			for (i = 0; i<SWN; i++)
				printf("%-15s's average is: %.2f.\n", schoolwork[i], (float)total[i] / n);
			break;

		/* 计算总分 */
		case 't': 
		case 'T':
			if ((n = totalmark(stuf)) == 0)
			{
				puts("Error!");
				break;
			}
			printf("\n");
			for (i = 0; i<SWN; i++)
				printf("%-15s's total mark is: %d.\n", schoolwork[i], total[i]);
			break;

		/* 按学生的姓名寻找记录 */
		case 'n': 
		case 'N':
			printf("Please input the student's name you want to search: ");
			scanf("%s", buf);
			retrievebyn(stuf, buf);
			break;

		/* 按学生的学号寻找记录 */
		case 'c': 
		case 'C':
			printf("Please input the student's code you want to search: ");
			scanf("%s", buf);
			retrievebyc(stuf, buf);
			break;

		/* 列出所有学生记录 */
		case 'l':
		case 'L':
			liststu(stuf);
			break;

		/* 按总分从高到低排列显示 */
		case 's':
		case 'S':
			if ((head = makelist(stuf)) != NULL)
				displaylist(head);
			break;
		default: break;
		}
	}
}

42、插入排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 255
int R[MAX];

/** 对数组R中的记录R[1..n]按递增序进行插入排序  */
void Insert_Sort(int n)
{ 
	int i, j;
	for (i = 2; i <= n; i++) /* 依次插入R[2],…,R[n] */
		if (R[i]<R[i - 1])			// 若前面的大于后面的
		{
			R[0] = R[i];			/* 应在原有位置上 */
			j = i - 1;				/* R[0]是哨兵,且是R[i]的副本 */

			/* 从右向左在有序区R[1..i-1]中查找R[i]的插入位置 */
			do{						
				R[j + 1] = R[j];	/* 将关键字大于R[i]的记录后移 */
				j--;
			} while (R[0]<R[j]);	/* 当R[i]≥R[j]时终止 */
			R[j + 1] = R[0];		/* R[i]插入到正确的位置上 */
		}
}


// R[0] 暂不存储数据,用来排序暂存数据
void main()
{
	int i, n;
	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	printf("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Insert_Sort(n);
	printf("\nThe sequence after insert_sort is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	system("pause");
}

43、希尔排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 255
int R[MAX];

/* 采用自下向上扫描,对R做冒泡排序,将R[0]作为存储单元 */
void Bubble_Sort(int n)
{ 
	int i, j;		
	int flag;								/* 交换标志 */

	for (i = 1; i < n; i++){				/* 最多做n-1趟排序 */
		flag = 0;							/* 本趟排序开始前,交换标志应为假 */
		for (j = n - 1; j >= i; j--)		/* 对当前无序区R[i..n]自下向上扫描 */
			if (R[j + 1] < R[j]){			/* 交换记录 */
				R[0] = R[j + 1];			/* R[0]不是哨兵,仅做暂存单元 */
				R[j + 1] = R[j];
				R[j] = R[0];
				flag = 1;					/* 发生了交换,故将交换标志置为真 */
			}
		if (!flag)							/* 本趟排序未发生交换,提前终止算法 */
			return;
	}
}

void main()
{
	int i, n;
	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	printf("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Bubble_Sort(n);
	printf("\nThe sequence after bubble_sort is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);

	system("pause");
}

44、冒泡排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>


#define MAX 255
int R[MAX];

/** 调用Partition(R,low,high)时,对R[low..high]做划分 */
int Partition(int i, int j)
{
	/* 并返回基准记录的位置 */
	int pivot = R[i];			/* 用区间的第1个记录作为基准 */
	while (i < j){				/* 从区间两端交替向中间扫描,直至i=j为止 */
		while (i < j && R[j] >= pivot) /* pivot相当于在位置i上 */
			j--;				/* 从右向左扫描,查找第1个关键字小于pivot.key的记录R[j] */
		if (i < j)				/* 表示找到的R[j]的关键字<pivot.key  */
			R[i++] = R[j];		/* 相当于交换R[i]和R[j],交换后i指针加1 */
		while (i < j && R[i] <= pivot) /* pivot相当于在位置j上*/
			i++;				/* 从左向右扫描,查找第1个关键字大于pivot.key的记录R[i] */
		if (i < j)				/* 表示找到了R[i],使R[i].key>pivot.key */
			R[j--] = R[i];		/* 相当于交换R[i]和R[j],交换后j指针减1 */
	} 
	R[i] = pivot;				/* 基准记录已被最后定位*/
	return i;
} 

/* 对R[low..high]快速排序 */
void Quick_Sort(int low, int high)
{ 
	int pivotpos;								/* 划分后的基准记录的位置 */

	if (low < high){							/* 仅当区间长度大于1时才须排序 */
		pivotpos = Partition(low, high);		/* 对R[low..high]做划分 */
		Quick_Sort(low, pivotpos - 1);			/* 对左区间递归排序 */
		Quick_Sort(pivotpos + 1, high);			/* 对右区间递归排序 */
	}
} 


void main()
{
	int i, n;
	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	puts("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Quick_Sort(1, n);
	printf("\nThe sequence after quick_sort is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	system("pause");
}

45、快速排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 255
int R[MAX];

/* 希尔排序中的一趟排序,d为当前增量 */
void ShellPass(int d, int n)
{
	int i, j;
	for (i = d + 1; i <= n; i++)	/* 将R[d+1..n]分别插入各组当前的有序区 */
	if (R[i]<R[i - d])
	{
		R[0] = R[i]; j = i - d;		/* R[0]只是暂存单元,不是哨兵 */
		do {						/* 查找R[i]的插入位置 */
			R[j + d] = R[j];		/* 后移记录 */
			j = j - d;				/* 查找前一记录 */
		} while (j>0 && R[0]<R[j]);
		R[j + d] = R[0];			/* 插入R[i]到正确的位置上 */
	}
} 

void  Shell_Sort(int n)
{
	int increment = n;					/* 增量初值,不妨设n>0 */
	do {
		increment = increment / 3 + 1;  /* 求下一增量 */
		ShellPass(increment, n);		/* 一趟增量为increment的Shell插入排序 */
	} while (increment > 1);
} 


void main()
{
	int i, n;

	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	printf("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Shell_Sort(n);
	printf("\nThe sequence after shell_sort is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	system("pause");
}

46、选择排序


#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 255
int R[MAX];


void Select_Sort(int n)
{
	int i, j, k;
	for (i = 1; i<n; i++)
	{/* 做第i趟排序(1≤i≤n-1) */
		k = i;
		for (j = i + 1; j <= n; j++)	/* 在当前无序区R[i..n]中选key最小的记录R[k] */
		if (R[j]<R[k])
			k = j;						/* k记下目前找到的最小关键字所在的位置 */
		if (k != i)
		{								/* 交换R[i]和R[k] */
			R[0] = R[i]; R[i] = R[k]; R[k] = R[0]; /* R[0]作暂存单元 */
		} 
	} 
} 

void main()
{
	int i, n;
	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	printf("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Select_Sort(n);
	printf("\nThe sequence after select_sort is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	system("pause");
}

47、堆排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 255
int R[MAX];

void Heapify(int s, int m)
{
	int j, temp;			/*对R[1..n]进行堆调整,用temp做暂存单元 */
	temp = R[s];
	j = 2 * s;
	while (j <= m)
	{
		if (R[j] > R[j + 1] && j<m) j++;
		if (temp < R[j]) break;
		R[s] = R[j];
		s = j;
		j = j * 2;
	}
	R[s] = temp;
} 


/* 由一个无序的序列建成一个堆 */
void BuildHeap(int n)
{
	int i;
	for (i = n / 2; i>0; i--)
		Heapify(i, n);
}

/* 对R[1..n]进行堆排序,不妨用R[0]做暂存单元 */
void Heap_Sort(int n)
{
	int i;
	BuildHeap(n);									/* 将R[1-n]建成初始堆 */
	for (i = n; i>1; i--)
	{												/* 对当前无序区R[1..i]进行堆排序,共做n-1趟。 */
		R[0] = R[1]; R[1] = R[i]; R[i] = R[0];		/* 将堆顶和堆中最后一个记录交换 */
		Heapify(1, i - 1);							/* 将R[1..i-1]重新调整为堆,仅有R[1]可能违反堆性质 */
	} 
} 
void main()
{
	int i, n;
	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	printf("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Heap_Sort(n);
	printf("\nThe sequence after Big heap_sort is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	system("pause");
}

48、归并排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 255
int R[MAX];

/* 将两个有序的子文件R[low..m)和R[m+1..high]归并成一个有序的 */
void Merge(int low, int m, int high)
{
	/* 子文件R[low..high] */
	int i = low, j = m + 1, p = 0;		/* 置初始值 */
	int *R1;							/* R1是局部向量,若p定义为此类型指针速度更快 */
	R1 = (int *)malloc((high - low + 1)*sizeof(int));
	if (!R1)							/* 申请空间失败 */
	{
		puts("Insufficient memory available!");
		return;
	}
	while (i <= m&&j <= high)			/* 两子文件非空时取其小者输出到R1[p]上 */
		R1[p++] = (R[i] <= R[j]) ? R[i++] : R[j++];
	while (i <= m)						/* 若第1个子文件非空,则复制剩余记录到R1中 */
		R1[p++] = R[i++];
	while (j <= high)					/* 若第2个子文件非空,则复制剩余记录到R1中 */
		R1[p++] = R[j++];
	for (p = 0, i = low; i <= high; p++, i++)
		R[i] = R1[p];					/* 归并完成后将结果复制回R[low..high] */
} 

/* 用分治法对R[low..high]进行二路归并排序 */
void Merge_SortDC(int low, int high)
{
	int mid;
	if (low<high)	/* 区间长度大于1 */
	{									
		mid = (low + high) / 2;			/* 分解 */
		Merge_SortDC(low, mid);			/* 递归地对R[low..mid]排序 */
		Merge_SortDC(mid + 1, high);	/* 递归地对R[mid+1..high]排序 */
		Merge(low, mid, high);			/* 组合,将两个有序区归并为一个有序区 */
	}
}


void main()
{
	int i, n;
	printf("Please input total element number of the sequence:");
	scanf("%d", &n);
	if (n <= 0 || n>MAX)
	{
		printf("n must more than 0 and less than %d.\n", MAX);
		exit(0);
	}
	printf("Please input the elements one by one:");
	for (i = 1; i <= n; i++)
		scanf("%d", &R[i]);
	printf("The sequence you input is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	Merge_SortDC(1, n);
	printf("\nThe sequence after merge_sortDC is:");
	for (i = 1; i <= n; i++)
		printf("%4d", R[i]);
	system("pause");
}

49、基数排序

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 5

// 链表
typedef struct node
{
	int k;
	struct node *next;
} *lnode;

// 输入函数
lnode my_input(int *d)
{
	lnode head, temp, terminal;	 // 头节点、临时结点、尾结点
	char s[MAX + 1];
	printf("Input the records ('0' to end input):");
	scanf("%s", s);
	head = NULL;
	*d = 0;
	terminal = NULL;
	while (s[0] != '0')
	{
		temp = (lnode)malloc(sizeof(struct node));
		if (strlen(s) > *d)
			*d = strlen(s);
		temp->k = atoi(s);
		if (head == NULL)
		{
			head = temp;
			terminal = temp;
		}
		else
		{
			terminal->next = temp;
			terminal = temp;
		}
		scanf("%s", s);
	}
	terminal->next = NULL;

	return head;
}

void my_output(lnode h)
{
	lnode t = h;	// 将h暂存,后循环为了不然h的指向改变
	printf("\n");
	while (t != NULL)
	{
		printf("%d ", t->k);
		t = t->next;
	}
}

/* 排序函数 */
lnode Radix_Sort(lnode head, int d)
{
	lnode p, q, h, t;
	int i, j, x, radix = 1;

	h = (lnode)malloc(10 * sizeof(struct node));
	t = (lnode)malloc(10 * sizeof(struct node));

	for (i = d; i >= 1; i--)
	{
		for (j = 0; j <= 9; j++)
		{
			h[j].next = NULL;
			t[j].next = NULL;
		}
		p = head;
		while (p != NULL)
		{
			x = ((p->k) / radix) % 10;
			if (h[x].next == NULL)
			{
				h[x].next = p;
				t[x].next = p;
			}
			else
			{
				q = t[x].next;
				q->next = p;
				t[x].next = p;
			}
			p = p->next;
		}

		j = 0;
		while (h[j].next == NULL)
			j++;
		head = h[j].next;
		q = t[j].next;
		for (x = j + 1; x <= 9; x++)
		if (h[x].next != NULL)
		{
			q->next = h[x].next;
			q = t[x].next;
		}
		q->next = NULL;
		radix *= 10;
		printf("\n---------------------\n");
	}
	return head;
}

/* 释放空间 */
void my_free(lnode h)
{
	lnode temp = h;
	while (temp)
	{
		h = temp->next;
		free(temp);
		temp = h;
	}
}

void main()
{
	lnode h;
	int d;
	h = my_input(&d);
	puts("The sequence you input is:");
	my_output(h);
	h = Radix_Sort(h, d);
	puts("\nThe sequence after radix_sort is:");
	my_output(h);
	my_free(h);
	system("pause");
}

50、二叉树操作

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

/* 节点 */
struct node {
	int				value;
	struct node* 	left;
	struct node* 	right;
};

typedef struct node  NODE;
typedef struct node* PNODE;

/* 创建新节点 */
void new_node(PNODE* n, int value) {

	*n = (PNODE)malloc(sizeof(NODE));
	if (*n != NULL) {
		(*n)->value = value;
		(*n)->left = NULL;
		(*n)->right = NULL;
	}
}

/* 释放空间 */
void free_node(PNODE* n) {
	if ((*n) != NULL) {
		free(*n);
		*n = NULL;
	}
}

/* 释放树 */
void free_tree(PNODE* n) {
	if (*n == NULL) return;
	if ((*n)->left != NULL) {
		free_tree(&((*n)->left));
	}
	if ((*n)->right != NULL) {
		free_tree(&((*n)->right));
	}
	free_node(n);
}
/* 查找结点 */
PNODE find_node(PNODE n, int value) {
	if (n == NULL) {
		return NULL;
	}
	else if (n->value == value) {
		return n;
	}
	else if (value <= n->value) {
		return find_node(n->left, value);
	}
	else {
		return find_node(n->right, value);
	}
}
/* 插入结点 */
void insert_node(PNODE* n, int value) {
	if (*n == NULL) {
		new_node(n, value);
	}
	else if (value == (*n)->value) {
		return;
	}
	else if (value < (*n)->value) {
		insert_node(&((*n)->left), value);
	}
	else {
		insert_node(&((*n)->right), value);
	}
}
/* 最长路径 */
int get_max_depth(PNODE n) {
	int left = 0;
	int right = 0;
	if (n == NULL) {
		return 0;
	}
	if (n->left != NULL) {
		left = 1 + get_max_depth(n->left);
	}
	if (n->right != NULL) {
		right = 1 + get_max_depth(n->right);
	}
	return (left > right ? left : right);
}
/* 最短路径 */
int get_min_depth(PNODE n) {
	int left = 0;
	int right = 0;
	if (n == NULL) {
		return 0;
	}
	if (n->left != NULL) {
		left = 1 + get_min_depth(n->left);
	}
	if (n->right != NULL) {
		right = 1 + get_min_depth(n->right);
	}
	return (left < right ? left : right);
}

/* 获取节点数目 */
int get_num_nodes(PNODE n) {
	int left = 0;
	int right = 0;
	if (n == NULL) {
		return 0;
	}
	if (n->left != NULL) {
		left = get_num_nodes(n->left);
	}
	if (n->right != NULL) {
		right = get_num_nodes(n->right);
	}
	return (left + 1 + right);
}
/* 最短路径长度 */
int get_min_value(PNODE n) {
	if (n == NULL) return 0;
	if (n->left == NULL) {
		return n->value;
	}
	else {
		return get_min_value(n->left);
	}
}
/* 最长路径长度 */
int get_max_value(PNODE n) {
	if (n == NULL) return 0;
	if (n->right == NULL) {
		return n->value;
	}
	else {
		return get_max_value(n->right);
	}
}
/* 删除结点 */
void deletenode(PNODE *n) {
	PNODE tmp = NULL;
	if (n == NULL) return;
	if ((*n)->right == NULL) {
		tmp = *n;
		*n = (*n)->left;
		free_node(n);
	}
	else if ((*n)->left == NULL) {
		tmp = *n;
		*n = (*n)->right;
		free_node(n);
	}
	else {
		for (tmp = (*n)->right; tmp->left != NULL; tmp = tmp->left);
		tmp->left = (*n)->left;
		tmp = (*n);
		*n = (*n)->right;
		free_node(&tmp);
	}
}

/* 根据值删除节点 */
void delete_node(PNODE *n, int value) {
	PNODE node;
	if (n == NULL) return;
	node = find_node(*n, value);
	if ((*n)->value == value) {
		deletenode(n);
	}
	else if (value < (*n)->value) {
		delete_node(&((*n)->left), value);
	}
	else {
		delete_node(&((*n)->right), value);
	}
}

/* 前序遍历 */
void pre_order_traversal(PNODE n)
{
	if (n != NULL) {
		printf("%i ", n->value);
		pre_order_traversal(n->left);
		pre_order_traversal(n->right);
	}
}

/* 中序遍历 */
void in_order_traversal(PNODE n)
{
	if (n != NULL) {
		in_order_traversal(n->left);
		printf("%i ", n->value);
		in_order_traversal(n->right);
	}
}

/* 后序遍历 */
void post_order_traversal(PNODE n)
{
	if (n != NULL) {
		post_order_traversal(n->left);
		post_order_traversal(n->right);
		printf("%i ", n->value);
	}
}

int main() {
	char buf[50];
	int  option;
	PNODE tree = NULL;
	PNODE node = NULL;
	while (1) {
		printf("--------------------------\n");
		printf("Options are:\n\n");
		printf(" 0  Exit\n");
		printf(" 1  Insert node\n");
		printf(" 2  Delete node\n");
		printf(" 3  Find node\n");
		printf(" 4  Pre order traversal\n");
		printf(" 5  In order traversal\n");
		printf(" 6  Post order traversal\n");
		printf(" 7  Max depth\n");
		printf(" 8  Min depth\n");
		printf(" 9  Max value\n");
		printf(" 10 Min value\n");
		printf(" 11 Node Count\n\n");
		printf("--------------------------\n");
		printf("Select an option: ");
		fgets(buf, sizeof(buf), stdin);
		sscanf(buf, "%i", &option);
		printf("--------------------------\n");
		if (option < 0 || option > 11) {
			fprintf(stderr, "Invalid option");
			continue;
		}
		switch (option) {
		case 0:
			exit(0);
		case 1:
			printf("Enter number to insert: ");
			fgets(buf, sizeof(buf), stdin);
			sscanf(buf, "%i", &option);
			printf("\n\n");
			insert_node(&tree, option);
			break;
		case 2:
			printf("Enter number to delete: ");
			fgets(buf, sizeof(buf), stdin);
			sscanf(buf, "%i", &option);
			printf("\n\n");
			delete_node(&tree, option);
			break;
		case 3:
			printf("Enter number to find: ");
			fgets(buf, sizeof(buf), stdin);
			sscanf(buf, "%i", &option);
			printf("\n\n");
			node = find_node(tree, option);
			if (node != NULL) {
				printf("Found node\n\n");
			}
			else {
				printf("Couldn't find node\n\n");
			}
			break;
		case 4:
			printf("Pre order traversal: ");
			pre_order_traversal(tree);
			printf("\n\n");
			break;
		case 5:
			printf("In order traversal: ");
			in_order_traversal(tree);
			printf("\n\n");
			break;
		case 6:
			printf("Post order traversal: ");
			post_order_traversal(tree);
			printf("\n\n");
			break;
		case 7:
			printf("Max depth is %i\n\n", get_max_depth(tree));
			break;
		case 8:
			printf("Min depth is %i\n\n", get_min_depth(tree));
			break;
		case 9:
			printf("Max value is %i\n\n", get_max_value(tree));
			break;
		case 10:
			printf("Min value is %i\n\n", get_min_value(tree));
			break;
		case 11:
			printf("Node Count is %i\n\n", get_num_nodes(tree));
			break;
		}
	}
	return 0;
}

51、二项式系数递归

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

int binom(int n, int i);
void main(void)
{
	int int1;
	int int2;
	//打印两项式
	printf("NOTE: Entering a figure other than a number will \ncause the program to crash.");
	printf("Formula computation is in B(n,i) N, 1st integer >= 2nd, I, Integer.\n");
	printf("n!\n");
	printf("B(n,i)= ----------\n");
	printf("k!(n-i)!\n");
	printf("Warning: Program has no error checking!\n");
	printf("Enter an integer :");
	scanf("%d", &int1);
	printf("Enter a second integer :");
	scanf("%d", &int2);
	printf("Binomial Coefficiant : %d", binom(int1, int2));

	system("pause");
}
//算法计算
int binom(int n, int i)
{
	int n1;
	int n2;
	if ((i == 0) || (n == i))
	{
		return 1;
	}
	else
	{
		n1 = binom(n - 1, i);
		n2 = binom(n - 1, i - 1);
		return n1 + n2;
	}
}

52、背包问题


#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define MAX 100

struct Bag
{
	int weight;
	int value;
}Bag[MAX];

int a[MAX];
int Value = 0;
int Weight;

int comb(int m, int k)
{
	int i, j;
	int wei, val;
	for (i = m; i >= k; i--)
	{
		a[k] = i;
		if (k>1)
			comb(i - 1, k - 1);
		else
		{
			wei = 0;							/* 预值0 */
			val = 0;
			for (j = a[0]; j>0; j--)            /* 每一种组合求它们的重量和价值 */
			{
				wei = wei + Bag[a[j]].weight;
				val = val + Bag[a[j]].value;
			}
			if (wei <= Weight && val>Value)		/* 判断是否满足条件进行附值 */
				Value = val;
		}
	}
	return Value;
}
void main()
{
	int num, subnum;
	int l;

	printf("输入背包的总个数:");								/* 输入背包的总个数 */
	scanf("%d", &num);
	printf("输入背包的重量和价值", num);						/* 输入背包的重量和价值 */
	for (l = 1; l <= num; l++)
		scanf("%d,%d", &Bag[l].weight, &Bag[l].value);
	printf("输入满足要求背包的个数:");						/* 输入要求背包的个数 */
	scanf("%d", &subnum);
	printf("输入满足条件的重量:", subnum);					/* 输入满足条件的重量*/
	scanf("%d", &Weight);
	a[0] = subnum;
	printf("the max value is:%d", comb(num, subnum));
	system("pause");
}

53、顺序表插入和删除

#define ListSize 100/* 假定表空间大小为100 */
#include <stdio.h>
#include <stdlib.h>

/* 从0开始计, 表空间大小应为101了 */
void Error(char * message)
{
	printf("错误:%s\n", message);
	exit(1);
}
struct Seqlist{
	int  data[ListSize];	/* 向量data用于存放表结点 */
	int length;				/*  当前的表长度 */
};


/** 
* @func:将新结点x插入L所指的顺序表的第i个结点ai的位置上
* @param x:新结点
* @param i:插入的位置
*/
void InsertList(struct Seqlist *L, int x, int i)
{
	
	int j;
	if (i < 0 || i > L->length)
		Error("position error");/* 非法位置,退出 */
	if (L->length >= ListSize)
		Error("overflow");
	for (j = L->length - 1; j >= i; j--)
		L->data[j + 1] = L->data[j];
	L->data[i] = x;
	L->length++;
}

/** 
* @func从L所指的顺序表中删除第i个结点ai
* @param i:删除的位置
*/
void DeleteList(struct Seqlist *L, int i)
{
	int j;
	if (i< 0 || i > L->length - 1)
		Error(" position error");
	for (j = i + 1; j < L->length; j++)
		L->data[j - 1] = L->data[j]; /* 结点前移 */
	L->length--; /* 表长减小 */
}

/** 初始化链表 */
void Initlist(struct Seqlist *L)
{
	L->length = 0;
}

void main()
{
	/* 创建并初始化链表 */
	struct Seqlist *SEQA;
	int i;
	SEQA = (struct Seqlist *)malloc(sizeof(struct Seqlist));
	Initlist(SEQA);

	/* 插入数据 */ 
	for (i = 0; i<ListSize; i++)
	{
		InsertList(SEQA, i, i);
		printf("%d\n", SEQA->data[i]);
	}
	/* 删除数据 */
	DeleteList(SEQA, 99);

	/* 打印数据 */
	for (i = 0; i<ListSize - 1; i++)
	{
		printf("%d\n", SEQA->data[i]);
	}
}

54、链表操作(1)

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define N 10


/** 链表结构 */
typedef struct node
{
	char name[20];
	struct node *link;
}stud;

/* 创建链表 */
stud * creat_link()
{
	stud *p, *head, *s;
	int i, n;
	printf("Please input the number of linklist:");
	scanf("%d", &n);
	/* 创建头结点 */
	if ((head = (stud *)malloc(sizeof(stud))) == NULL)
	{
		printf("cannot find space!");
		exit(0);
	}
	head->name[0] = '\0';
	head->link = NULL;
	p = head;

	/* 循环创建多个结点 */
	for (i = 0; i<n; i++)
	{
		if ((s = (stud *)malloc(sizeof(stud))) == NULL)
		{
			printf("cannot find space!");
			exit(0);
		}
		p->link = s;
		printf("please input %d student's name: ", i + 1);
		scanf("%s", s->name);
		s->link = NULL;
		p = s;
	}

	return head;
}

/** 查找相应的值 */
stud * search(stud *h, char *x)
{
	stud *p;
	char *y;
	p = h->link;
	while (p != NULL)
	{
		y = p->name;
		if (strcmp(y, x) == 0)
			return(p);
		else p = p->link;
	}
	if (p == NULL)
		printf("data not find!");
	return 0;
}


stud * search2(stud *h, char *x)
{
	stud *p, *s;
	char *y;
	p = h->link;
	s = h;
	while (p != NULL)
	{
		y = p->name;
		if (strcmp(y, x) == 0)
			return(s);
		else
		{
			p = p->link;
			s = s->link;
		}
	}
	if (p == NULL)
		printf("data not find!");
	return 0;
}


/* 插入数据 */
void insert_node(stud *p)
{
	char stuname[20];
	stud *s;
	if ((s = (stud *)malloc(sizeof(stud))) == NULL)
	{
		printf("cannot find space!");
		exit(0);
	}
	printf("please input the student's name: ");
	scanf("%s", stuname);
	strcpy(s->name, stuname);
	s->link = p->link;
	p->link = s;
}

/** 删除数据 */
void del_node(stud *x, stud *y)
{
	stud *s;
	s = y;
	x->link = y->link;
	free(s);
}

/* 打印数据 */
void my_print(stud *h)
{
	stud *p;
	p = h->link;
	printf("Now the link list is:\n");
	while (p != NULL)
	{
		printf("%s ", &*(p->name));
		p = p->link;
	}
	printf("\n");
}

/** 退出函数 */
void quit()
{
	puts("\n Thank you for your using!\n Press any key to quit...");
	exit(0);
}

/** 菜单 */
void menu(void)
{
	printf("       simple linklise realization of c\n");
	printf("    ||=====================================||\n");
	printf("    ||                                     ||\n");
	printf("    || [1]  create linklist                ||\n");
	printf("    || [2]  seach                          ||\n");
	printf("    || [3]  insert                         ||\n");
	printf("    || [4]  delete                         ||\n");
	printf("    || [5]  print                          ||\n");
	printf("    || [6]  exit                           ||\n");
	printf("    ||                                     ||\n");
	printf("    || if no list exist,create first       ||\n");
	printf("    ||                                     ||\n");
	printf("    ||=====================================||\n");
	printf("      Please input your choose(1-6): ");
}

void main()
{
	int choose;
	stud *head, *searchpoint, *forepoint;
	char fullname[20];


	while (1)
	{
		menu();
		scanf("%d", &choose);
		switch (choose)
		{
		case 1:
			head = creat_link();
			puts("Linklist created successfully! \nPress any key to return...");
			getchar();
			break;
		case 2:
			printf("Input the student's name which you want to find:\n");
			scanf("%s", fullname);
			searchpoint = search(head, fullname);
			printf("The stud name you want to find is:%s", *&searchpoint->name);
			getchar();
			getchar();
			break;
		case 3:
			insert_node(head);
			my_print(head);
			getchar(); getchar();
			break;
		case 4:
			my_print(head);
			printf("\nInput the student's name which you want to delete:\n");
			scanf("%s", fullname);
			searchpoint = search(head, fullname);
			forepoint = search2(head, fullname);
			del_node(forepoint, searchpoint);
			my_print(head);
			puts("\nDelete successfully! Press any key to return...");
			getchar();
			getchar();
			break;
		case 5:my_print(head);
			getchar(); getchar();
			break;
		case 6:quit();
			break;
		default:
			printf("Illegal letter! Press any key to return...");
			menu();
			getchar();
		}
	}
}

55、链表操作(2)

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define List_INIT_SIZE  100   //线性表的存储空间初始大小
#define LIST_INCREMENT  10    //分配增量
#define OVERFLOW   -2
#define OK     1
#define ERROR    -1
#define TRUE    1
#define FALSE    0
typedef int  ElemType;


typedef struct{
	ElemType *elem;  //存储空间基址
	int   length;    //当前长度
	int   size;      //当前存储容量(sizeof(ElemType)为单位)
}SqList;

/** 初始化链表 */
int InitList(SqList &L)
{
	//构建一个线性表L
	L.elem = (ElemType*)malloc(List_INIT_SIZE*sizeof(ElemType));
	if (!L.elem)
	{
		exit(OVERFLOW);
	}
	L.length = 0;				// 长度初始化为0
	L.size = List_INIT_SIZE;	// 初始化容量
	return OK;
}

/** 销毁链表 */
void DestoryList(SqList &L)
{
	if (!L.elem)
	{
		delete L.elem;		// 释放空间
		L.elem = NULL;
	}
	L.length = 0;			// 长度及容量置为0
	L.size = 0;
}

/** 清空链表 */
void ClearList(SqList &L)
{
	L.elem = NULL;	
	L.length = 0;
	L.size = List_INIT_SIZE;
}

/* 判断链表是否为空 */
int isEmpty(SqList L)
{
	if (L.length > 0)
	{
		return TRUE;
	}
	else
	{
		return FALSE;
	}
}

/** 获取链表长度 */
int ListLength(SqList L)
{
	return L.length;
}

/** 插入数据 */
int ListInsert(SqList &L, int i, ElemType e)
{
	if (i<1 || i>ListLength(L) + 1)		// 需满足条件1<i<ListLength(L)+1
	{
		return ERROR;
	}
	ElemType * NewBase;					// 新的基址
	if (L.length > L.size)				//空间已满
	{
		NewBase = (ElemType*)malloc((L.size + LIST_INCREMENT)*sizeof(ElemType));  //申请新的空间
		if (!NewBase)
		{
			exit(OVERFLOW);
		}
		L.elem = NewBase;				// 将新的数据存入
		L.size += LIST_INCREMENT;		// 增加一倍的容量
		delete NewBase;
		NewBase = NULL;
	}
	ElemType *p;
	ElemType *temp;
	p = &(L.elem[i - 1]);				//取得i的位置,即插入位置
	for (temp = &(L.elem[L.length - 1]); temp>p; --temp)  //将插入点后的所有元素向后移动一位
	{
		*(temp + 1) = *temp;
	}
	*p = e;
	++L.length;
	return OK;
}

/* 根据数值删除 */
int ListDelete(SqList &L, int i, ElemType &e)
{
	if (i<0 || i>ListLength(L)) {
		return ERROR;
	}
	ElemType *p;
	p = &(L.elem[i - 1]);
	e = *p;
	ElemType *pos;
	pos = &(L.elem[L.length - 1]);
	for (++p; p <= pos; ++p){
		*(p - 1) = *p;
	}
	--L.length;
	return OK;
}


void main(){
	SqList list;
	ElemType e;
	InitList(list);			// 初始化
	ListInsert(list, 1, 1);
	ListInsert(list, 2, 2);
	ListInsert(list, 3, 3);
	ListInsert(list, 4, 4);
	ListInsert(list, 5, 5);	// 插入数据
	for (int i = 0; i<list.length; i++){
		printf("%d\n", list.elem[i]);
	}

	ListDelete(list, 2, e);
	for (int i = 0; i<list.length; i++){
		printf("%d\n", list.elem[i]);
	}	printf("%d\n", list.length);

	system("pause");
}

56、单链表就地逆置

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define NULL 0 /* 宏定义 */

/** 定义结点类型的数据结构 */
typedef struct node 
{
	char c;				/* 数据域,类型为字符型 */
	struct node *next;	/* 指针域,类型为本结构体类型 */
}Node, *L;				/* 类型重定义,即Node和*L和struct node等价 */

void main()
{
	L l, p, q, r;					/*用 指针类型定义三个结点类型的指针 */
	char ch;
	l = (L)malloc(sizeof(Node));	/* 分配内存空间 */
	l->c = '\0';					/* 为头结点的数据域赋值,值为空 */
	l->next = NULL;					/* 指明下一个结点目前不存在 */
	q = l;							/* q为游动指针,链表结点的连结要用 */
	printf("Input a character:\n");
	scanf("%c", &ch);
	getchar();
	while (ch != '0')				/* 输入0表示输入结束 */
	{
		p = (L)malloc(sizeof(Node));	/* 为新输入的数据分配内存空间 */
		p->c = ch;
		p->next = NULL;					/* 新输入的结点在链表的最后,即它的后面没有其它元素 */
		q->next = p;					/* q用于将上一个元素链接至当前新元素 */
		q = p;							/* q自己移到当前最后一个元素,以备继续链接所用 */
		scanf("%c", &ch);
		getchar();
	}

	/*以上完成了单链表的创建*/
	q = l->next;
	p = q->next;
	r = p->next;
	q->next = NULL;
	while (r != NULL)
	{
		p->next = q;
		q = p;
		p = r;
		if (r->next != NULL)			/* r后面还有结点,则逆置继续 */
			r = r->next;
		else
			break;
	}
	r->next = q;
	l->next = r;					// 头结点指向最后一个结点

	q = l;							/* 输入整个链表前,先将q移到链表头,l一般不动 */
	while (q->next != NULL)			/* 若q所指向的元素后面还有其它元素,则将该元素的数据输出 */
	{
		printf("%c-->", q->next->c); /* q->next->c表示q所指向的下一个元素的数据 */
		q = q->next;				 /* 完成该元素的输出后,q移至下一个元素重复输出操作 */
	}
	printf("\n");
	system("pause");
}

57、运动会分数统计

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define n 4
#define m 3
#define w 2

// 定义表示成绩的结构体
struct achievement  
{
	int schoolnumber;	//学校编号
	char name[20];		//姓名
	int mark;			//分数
	int result;
};

// 表示项目的结构体
struct pro     
{
	int tag;			//项目编号
	struct achievement ach[5];
	int number;
};

struct Node
{
	struct pro date;
	struct Node *next;
};

/** 初始化单链表 */
void ListInitiate(struct Node * *head)    
{
	if ((*head = (struct Node*)malloc(sizeof(struct Node))) == NULL) exit(1);
	(*head)->next = NULL;
}

void main()
{
	int i, j, t;
	int x[n] = { 0 }; int y[n] = { 0 };
	struct Node *head;
	struct Node *p;
	struct Node *q;
	ListInitiate(&head);
	p = head;

	/** 输入成绩 */
	for (i = 0; i<m + w; i++)      
	{
		j = i + 1;
		printf("请输入第%d个项目的信息\n", j);
		p->date.number = j;
		printf("所取的名次数为:");
		scanf("%d", &p->date.tag);
		while (p->date.tag != 3 && p->date.tag != 5)
		{
			printf("输入有误,请重新输入!");
			printf("所取的名次数为:");
			scanf("%d", &p->date.tag);
		}
		t = 1;
		while (t <= p->date.tag)
		{
			printf("第%d名的名字:", t);
			scanf("%s", &p->date.ach[t - 1].name);
			printf("第%d名的学校:", t);
			scanf("%d", &p->date.ach[t - 1].schoolnumber);
			printf("第%d名的分数:", t);
			scanf("%d", &p->date.ach[t - 1].mark);
			p->date.ach[t - 1].result = t;
			t++;
		}
		q = (struct Node*)malloc(sizeof(struct Node));  //生成新结点
		p->next = q;
		p = q;
		p->next = NULL;
	}

	/** 产生成绩单 */
	for (i = 0; i<n; i++)     
	{
		j = i + 1;
		printf("学校%d成绩单\n", j);
		p = head;
		do
		{
			t = 1;
			while (t <= p->date.tag)
			{
				if (p->date.ach[t - 1].schoolnumber == j)
				{
					printf("获奖项目:%d   ", p->date.number);
					printf("名次:%d   \n", p->date.ach[t - 1].result);
					printf("获奖人姓名:%s   ", p->date.ach[t - 1].name);
					printf("所得分数:%d   ", p->date.ach[t - 1].mark);
					if (p->date.number <= m)
						x[i] = x[i] + p->date.ach[t - 1].mark;
					else
						y[i] = y[i] + p->date.ach[t - 1].mark;
				}
				t++;
			}
			p = p->next;
		} while (p != NULL);
		printf("\n男子团体总分:%d   ", x[i]);
		printf("女子团体总分:%d   \n", y[i]);
		printf("\n团体总分:%d\n", x[i] + y[i]);
	}
}

58、双链表

#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#define N 10

/** 双链表的结构定义 */
typedef struct node
{
	char name[20];
	struct node *llink, *rlink;
}stud;

/** 双链表的创建 */
stud * creat(int n)
{
	stud *p, *h, *s;
	int i;
	/* 创建头结点 */
	if ((h = (stud *)malloc(sizeof(stud))) == NULL)
	{
		printf("cannot find space!\n");
		exit(0);
	}
	h->name[0] = '\0';
	h->llink = NULL;
	h->rlink = NULL;
	p = h;

	/* 循环插入数据 */
	for (i = 0; i<n; i++)
	{
		if ((s = (stud *)malloc(sizeof(stud))) == NULL)
		{
			printf("cannot find space!\n");
			exit(0);
		}
		p->rlink = s;
		printf("Please input the %d man's name: ", i + 1);
		scanf("%s", s->name);
		s->llink = p;
		s->rlink = NULL;
		p = s;
		h->llink = s;
	}
	p->rlink = h;

	return h;
}

/** 根据数值查找 */
stud * search(stud *h, char *x)
{
	stud *p;
	char *y;
	p = h->rlink;
	while (p != h)
	{
		y = p->name;
		if (strcmp(y, x) == 0)
			return(p);
		else p = p->rlink;
	}
	printf("cannot find data!\n");

	return NULL;
}

/** 打印输出 */
void print(stud *h)
{
	stud *p;
	p = h->rlink;
	printf("\nNow the double list is:\n");
	while (p != h)
	{
		printf("%s ", &*(p->name));
		p = p->rlink;
	}
	printf("\n");
}

/*删除*/
void del(stud *p)
{
	(p->rlink)->llink = p->llink;
	(p->llink)->rlink = p->rlink;
	free(p);
}

/*主函数*/
void main()
{
	int number;
	char studname[20];
	stud *head, *searchpoint;
	number = N;
	printf("Please input the size of the list:");
	scanf("%d", &number);
	head = creat(number);
	print(head);
	printf("\nPlease input the name which you want to find:");
	scanf("%s", studname);
	searchpoint = search(head, studname);
	printf("the name you want to find is:%s\n", *&searchpoint->name);
	del(searchpoint);
	print(head);
	system("pause");
}

59、约瑟夫环

#include<stdlib.h>
#include<string.h>
#include<stdio.h>

#define  N 7                                         //定义N=7,表示有7个链表单元
#define  OVERFLOW  0
#define  OK  1

/** 定义链表结构 */
typedef struct LNode{                             
	int password;
	int order;
	struct LNode *next;
}LNode, *LinkList;

int  PassW[N] = { 3, 1, 7, 2, 4, 8, 4 };
void  Joseph(LinkList p, int m, int x);          //声明函数

int main()
{
	int  i, m;
	LinkList  Lhead, p, q;						//定义三个指向链表结构的指针
	Lhead = (LinkList)malloc(sizeof(LNode));	//初始化头节点
	if (!Lhead)return OVERFLOW;                 //分配空间失败返回
	Lhead->password = PassW[0];
	Lhead->order = 1;
	Lhead->next = NULL;
	p = Lhead;

	/* 初始化循环列表中的密码值 */
	for (i = 1; i<7; i++){
		if (!(q = (LinkList)malloc(sizeof(LNode))))return OVERFLOW;
		q->password = PassW[i];                      
		q->order = i + 1;
		p->next = q; p = q;							 //新创建一个指针节点并使p->next指向它,再使p=q
	}
	p->next = Lhead;								 //使p->next指向头节点,从而形成循环链表
	printf("请输入第一次计数值m: ");
	scanf("%d", &m);                                 //用户输入第一次计数值m
	printf("第一次计数值m= %d \n", m);
	Joseph(p, m, N);
	return OK;
}


void  Joseph(LinkList p, int m, int x){
	LinkList q;
	int i;
	if (x == 0) return;                         // 链表中没有节点的话,立即返回上一层函数
	q = p;
	m %= x;										// m对x求余,从而求出链表中的第几个单元是所求节点
	if (m == 0)m = x;							// 若m刚好可以整除x,则令m=x,因为如果m=0,则不进行下一个
	// for循环,那样就无法使q指向要删除节点,p指向他的的前一节点,那样则无法进行删除操作  
	for (i = 1; i <= m; i++){
		p = q;
		q = p->next;							// 使q指向要删除的节点,p指向q的前一个节点
	}
	p->next = q->next;                          // 从循环链表中删除q指向的节点
	i = q->password;
	printf("%d  ", q->order);
	free(q);                                    // 释放q指向的空间
	Joseph(p, i, x - 1);
}

60、记录家庭资料


#include<stdlib.h>
#include<string.h>
#include<stdio.h>
#include <ctype.h>

/** 函数声明 */
struct Family *get_person(void);   
char related(struct Family *pmember1, struct Family *pmember2);
char set_ancestry(struct Family *pmember1, struct Family *pmember2);

/* 日期结构 */
struct Date
{
	int day;
	int month;
	int year;
};

/** 家族结构 */
struct Family                      
{
	struct Date dob;
	char name[20];
	char father[20];
	char mother[20];
	struct Family *next;            /* Pointer to next structure      */
	struct Family *previous;        /* Pointer to previous structure  */
	struct Family *p_to_pa;         /* Pointer to father structure   */
	struct Family *p_to_ma;         /* Pointer to mother structure   */
};

void main()
{
	struct Family *first = NULL;	// 头指针
	struct Family *current = NULL;  // 当前指针
	struct Family *last = NULL;     // 尾指针

	char more = '\0';              

	// 进入死循环
	while (1)
	{
		printf("Do you want to enter details of a%s person (Y or N)? ",
			first != NULL ? "nother " : "");
		scanf(" %c", &more);
		if (tolower(more) == 'n')
			break;

		current = get_person();

		if (first == NULL)
		{
			first = current;            /* Set pointer to first Family    */
			last = current;             /* Remember for next iteration    */
		}
		else
		{
			last->next = current;		/* Set next address for previous Family */
			current->previous = last;	/* Set previous address for current */
			last = current;				/* Remember for next iteration */
		}
	}

	current = first;

	while (current->next != NULL)		/* Check for relation for each person in    */
	{									/* the list up to second to last            */
		int parents = 0;				/* Declare parent count local to this block */
		last = current->next;			/* Get the pointer to the next              */

		while (last != NULL)			/* This loop tests current person           */
		{								/* against all the remainder in the list    */
			if (related(current, last))         /* Found a parent ?          */
			if (++parents == 2)			/* Yes, update count and check it        */
				break;					/* Exit inner loop if both parents found */

			last = last->next;			/* Get the address of the next           */
		}
		current = current->next;		/* Next in the list to check             */
	}

	/* 输出数据 */
	current = first;

	while (current != NULL)				/* Output Family data in correct order  */
	{
		printf("\n%s was born %d/%d/%d, and has %s and %s as parents.",
			current->name, current->dob.day, current->dob.month,
			current->dob.year, current->father, current->mother);
		if (current->p_to_pa != NULL)
			printf("\n\t%s's birth date is %d/%d/%d  ",
			current->father, current->p_to_pa->dob.day,
			current->p_to_pa->dob.month,
			current->p_to_pa->dob.year);
		if (current->p_to_ma != NULL)
			printf("and %s's birth date is %d/%d/%d.\n  ",
			current->mother, current->p_to_ma->dob.day,
			current->p_to_ma->dob.month,
			current->p_to_ma->dob.year);

		current = current->next;		/* current points to next in list       */
	}

	/* 释放空间 */
	current = first;
	while (current->next != NULL)
	{
		last = current;					/* Save pointer to enable memory to be freed */
		current = current->next;		/* current points to next in list       */
		free(last);						/* Free memory for last                      */
	}
}

/** 输入家庭成员 */
struct Family *get_person(void)
{
	/* 临时结构体 */
	struct Family *temp;         

	temp = (struct Family*) malloc(sizeof(struct Family));
	printf("Enter the name of the person: ");
	scanf("%s", temp->name);         /* 家族名称 */
	printf("Enter %s's date of birth (day month year); ", temp->name);
	scanf("%d %d %d", &temp->dob.day, &temp->dob.month, &temp->dob.year);
	printf("Who is %s's father? ", temp->name);
	scanf("%s", temp->father);        /* 父亲 */
	printf("Who is %s's mother? ", temp->name);
	scanf("%s", temp->mother);      /*母亲 */
	temp->next = temp->previous = NULL; /* Set pointers to NULL */
	temp->p_to_pa = temp->p_to_ma = NULL;    /* Set pointers to NULL  */
	return temp;    
}

/** 建立关系 */
char set_ancestry(struct Family *pmember1, struct Family *pmember2)
{
	if (strcmp(pmember1->father, pmember2->name) == 0)
	{
		pmember1->p_to_pa = pmember2;
		return 1;
	}
	if (strcmp(pmember1->mother, pmember2->name) == 0)
	{
		pmember1->p_to_ma = pmember2;
		return 1;
	}
	else
		return 0;
}

/** 返回关系 */
char related(struct Family *pmember1, struct Family *pmember2)
{
	return set_ancestry(pmember1, pmember2) ||
		set_ancestry(pmember2, pmember1);
}

  • 1
    点赞
  • 9
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Jxiepc

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值