笔试编程题2
1,统计输入的字符串的各个字母的数目,并按数目的大小输出,并显示所占百分比
主要是通过线性表的顺序表示和冒泡排序实现
/********************************************************************************* * Copyright: (C) 2014 zhoutian * All rights reserved. * * Filename: totalchar.c * Description: 统计输入的字符串的各个字母的数目,并按数目的大小输出,并显示所占百分比 * * Version: 1.0.0(2014年10月21日) * Author: zhoutian <zhoutian220@163.com> * ChangeLog: 1, Release initial version on "2014年11月08日 15时16分40秒" * ********************************************************************************/ #include <stdio.h> #include <stdlib.h> #define MAX 51 /* 输入的字符的最大值 */ #define LIST_INIT_SIZE 20 /*静态表存储空间的初始分配量 */ typedef struct { char alpha; int count; }ElemType; typedef struct { ElemType *elem; int total; //输入的总字母数 int num; //已使用的结点数 }SqList; //注意:函数声明放在结构体定义之后 int AddNode(SqList *list, char alpha); void total(SqList *list, char alpha); int ListSort(SqList *list); int ListShow(const SqList *list); /* */ int main (int argc, char **argv) { SqList list; char str[MAX]; int i = 0; list.num = list.total = 0; list.elem = (ElemType *)malloc(LIST_INIT_SIZE*sizeof(ElemType)); if(list.elem == NULL) { printf ("malloc error\n"); return -1; } printf ("input string(max number is:%d)\n",MAX-1); fgets(str,MAX-1,stdin); while(str[i] != '\0') { if(isalpha(str[i])) { total(&list, toupper(str[i])); list.total ++; } i++; } ListShow(&list); printf("after sort\n"); ListSort(&list); ListShow(&list); return 0; } /* ----- End of main() ----- */ /* 统计输入的各个字母的个数 */ void total(SqList *list, char alpha) { ElemType *elem = list->elem; int num = list->num; int i = 0; while(i<num && elem[i].alpha!=alpha) //遍历链表,查看是否有相同的字母 { i++; } if(elem[i].alpha == alpha) elem[i].count ++; //node不为空且找到等于alpha的字符,则该节点的count++ else AddNode(list,alpha); } /* 使用冒泡排序根据elem[i].count从小到大排序 */ int ListSort(SqList *list) { ElemType *elem = list->elem; ElemType temp; int num = list->num; int i = 0, j = 0; int exchange; for(i=0; i<num-1; i++) { exchange = 0; for(j=num-2; j>i; j--) { if(elem[j].count < elem[j+1].count) { temp = elem[j]; elem[j] = elem[j+1]; elem[j+1] = temp; exchange = 1; } if(exchange == 0) return 0; } } return 0; } int ListShow(const SqList *list) { ElemType *elem = list->elem; int num = list->num; int i; for(i=0; i<num; i++) { printf ("alpha %c: %d %.2f\n",elem[i].alpha, elem[i].count, (float)elem[i].count/list->total); } return 0; } /* 在静态表的末尾添加一个新的数据 */ int AddNode(SqList *list, char alpha) { ElemType *elem = list->elem; int num = list->num; elem[num].count = 1; elem[num].alpha = alpha; list->num ++; return 0; }