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

输入一个字符串,分别统计字符串中各字符出现个数,并将字符按个数从大到小输出,如果个数相同,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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值