问题描述完整代码
问题描述写一个算法统计在输入字符串中各个不同字符出现的频度并打印(字符串中的合法字符为A-Z这26个字母和0-9这10个数字)
完整代码#include#define MAXLEN 255 using namespace std; #include struct String { char str; struct String* next; String() {//初始化 str = {}; next = NULL; } }; struct SString { int length; String* head; String* tail; SString() {//初始化 length = 0; head = new String; tail = head; } }; class Printf { public: void Print(String* p) { printf("%cn", p->str);//打印递增序列 } }; class Sstring :public Printf { private: Printf printObj; public: String* creat(SString& SS, char* ch) { int i = 0; while (i != strlen(ch)) { if (SS.length == 0) { SS.head->str = ch[i]; SS.tail = SS.head; } else { SS.tail->next = new String; SS.tail->next->str = ch[i]; SS.tail = SS.tail->next; SS.tail->next = NULL; } i++; SS.length++; //printObj.Print(SS.tail); } return SS.head; } }; void Compare(SString& SS) { int i = 0; int k[MAXLEN] = { 0 };//用来保存字符频度 int length = 0; char c;//c用来保存需要计算的字符 String* p;//外循环移动 String* q1;//用于内循环 String* q2;//和删除字符 p = SS.head; if (SS.length == 0) printf("字符串为空,字符频度为0!"); while (p != NULL) { q1 = p; if ((q1->str >= 48 && q1->str <= 57) || (q1->str >= 65 && q1->str <= 90))//串中的合法字符才能进行频度计算 { length++;//有效字符长度加1 c = q1->str;//c来保存字符 k[i]++; if (q1 == SS.head) { SS.head = q1->next; q2 = q1; delete q2; q1 = SS.head; p = SS.head; } else { q2 = q1; q1 = q1->next; } while (q1 != NULL) { if (q1->str == c) { k[i]++; //n[i] = c; q2 = q1; q1 = q1->next; if (q2 == SS.head) { p = q1; SS.head = q1; } delete q2;//保存字符后就删除单链表中的字符 } else { q2 = q1; q1 = q1->next; } } i++; } } ofstream fout; fout.open("frequentness.txt", ios::app); cout << "各字符的频度为: n"; for (int m = 0; m <= i; m++) { fout << k[m] << "n"; cout << k[m] << "n"; } fout << flush; fout.close(); } int main() { Sstring S; SString SS; char ch[MAXLEN] ; gets_s(ch); String* head = S.creat(SS, ch); Compare(SS); }



