用C语言编程 字符串原地压缩。题目:“eeeeeaaaff" 压缩为 "e5a3f2"把s字符串压缩处理后结果保存在res中

如题所述

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>
#define MAX 50

typedef struct str
{
    char ch;
    int ccount;
    struct str *next;
}node;


node *func(char a[],int n);


int main()
{
    int index=0;
    node *head,*head2,*temp;
    char s[MAX],res[MAX];  //最大输入字符可以自己设置
    scanf("%s",s);
    head2=head=func(s,sizeof(s));
    while(head)
    {
        res[index++]=head->ch;
        res[index++]=head->ccount+48;
        head=head->next;
    }
    res[index]='\0';
    printf("\nres=%s",res);
    while(head2)
    {
        temp=head2->next;
        free(head2);
        head2=temp;
    }
    return 0;
}

node *func(char a[],int n)    //把结果放在链表中,返回链表头
{
    int i;
    node *temp,*head,*head2,*head3;
    bool new;
    for(i=0;i<n;i++)
    {
        if(i==0)
        {
            temp=(node *)malloc(sizeof(node));
            temp->ch=a[i];
            temp->ccount=0;
            temp->next=NULL;
            head=temp;
            head3=head2=temp;
        }
        while(head3)    //head3为了方便重置投指针
        {
            if(a[i]==head3->ch)
            {
                head3->ccount++;
                new=false;
                break;
            }
            head3=head3->next;
            new=true;
        }
        head3=head;
        if(new)        //head2指向最后一个链表
        {
            temp=(node *)malloc(sizeof(node));
            temp->ch=a[i];
            temp->ccount=1;
            temp->next=NULL;
            if((head2->next)!=NULL)
                head2=head2->next;
            head2->next=temp;
        }
    }
    return head;
}

温馨提示:答案为网友推荐,仅供参考
第1个回答  2014-08-12
#include<stdio.h>

void main()
{
char buf[1024]={0};
char res[1024]={0};
int i=0, j=0, len=0, cnt=0;

scanf("%s", buf);
len = strlen(buf);
for(; i<len; i++)
{
if(buf[i]==buf[i+1])
{
cnt++;
continue;
}
else
{
res[j++] = buf[i];
res[j++] = '0'+ cnt +1;
cnt = 0;
}
}

printf("res = %s\n", res);

}追问

输入aaaaaaaaaaaaiiiiiiiiijjjjj

输出是a<i9j5
不对啊。。。

追答

呵呵
这个只能玩玩
重复数字小于10个还可以玩
不支持大于10个 的

要做功能全面的 要好好付出的哦~

本回答被提问者和网友采纳
相似回答