分别统计字符串中各字符个数

来源:互联网 发布:物业管理系统源码 编辑:程序博客网 时间:2024/05/04 03:46
输入一个字符串,分别统计字符串中各字符出现个数,并将字符按个数从大到小输出,如果个数相同,ASCII值大的在前,如输入为DDdddFFFFffffnn时,输出为fFdnD。
#include <stdio.h>#include <stdlib.h>#include <string.h>typedef struct Node{    char ch;    int cnt;    struct Node *next;}node;node *createlist(){    node *strList=(node*)malloc(sizeof(node));    strList->next=NULL;    return strList;}int getlength(node *head){    int cnt=0;    node *p=head;    while(p->next!=NULL)    {        cnt++;        p=p->next;    }    return cnt;}void insertChar(node *head,char ch){    node *p=head;    if(p==NULL)        return;    while(p->next!=NULL)    {        p=p->next;        if(ch==p->ch)        {            p->cnt++;            return;        }    }    node *newNode=(node*)malloc(sizeof(node));    newNode->ch=ch;    newNode->cnt=1;    p->next=newNode;    newNode->next=NULL;}void sortList(node *head){    int i,j,tempCnt;    char tempChar;    int len=getlength(head);    node *p1,*p2;    if(len>1)    {        p1=head->next;        p2=p1->next;        for(i=0;i<len;i++)        {            p2=p1->next;            for(j=i+1;j<len;j++)            {                if(p1->cnt<p2->cnt)                {                    tempCnt=p2->cnt;                    tempChar=p2->ch;                    p2->cnt=p1->cnt;                    p2->ch=p1->ch;                    p1->cnt=tempCnt;                    p1->ch=tempChar;                }                else if(p1->cnt==p2->cnt)                {                    if(p1->ch<p2->ch)                    {                        tempChar=p2->ch;                        p2->ch=p1->ch;                        p1->ch=tempChar;                    }                }                p2=p2->next;            }            p1=p1->next;        }    }}int main(){    char str[2048];    int i,len;    node *p;    scanf("%[^\n]",str);    node *head=createlist();    p=head;    len=strlen(str);    for(i=0;i<len;i++)    {        insertChar(head,str[i]);    }    while(p->next!=NULL)    {        printf("%c",p->next->ch);        p=p->next;    }    printf("\n");    sortList(head);    p=head;    while(p->next!=NULL)    {        printf("%c",p->next->ch);        p=p->next;    }    return 0;}

0 0
原创粉丝点击