#include
#include
struct RleNode
{
int count;
char ch;
struct RleNode * next;
};
//压缩字符串
struct RleNode* encode(char *str)
{
char *ptr = str;
int num = 1;
int i = 0;
struct RleNode* head, *p, *q;
head = (struct RleNode*)malloc(sizeof(struct RleNode));
head->next = NULL;
p = head;
while(*ptr != '\0')
{
char ch = *ptr;
char ch2 = ptr[i];
char ch3 = ptr[i + 1];
if(ptr[i] == ptr[i + 1])
{
num++;
}
if((ptr[i] != ptr[i + 1]) )
{
q = (struct RleNode*)malloc(sizeof(struct RleNode));
q->count = num;
q->ch = ptr[i];
q->next = NULL;
p->next = q;
p = q;
num = 1;
}
ptr++;
}
return head;
}
//解压字符串
char *decode(struct RleNode* head)
{
char *str = calloc(1,100);
int num = 0;
int i = 0;
struct RleNode* p= head->next;
if(p == NULL)
{
printf("空表");
}
else
{
while(p->next != NULL)
{
num = p->count;
while(num > 0)
{
str[i] = p->ch;
i++;
num--;
}
p = p->next;
}
num = p->count;
while(num > 0)
{
str[i++] = p->ch;
num--;
}
}
return str;
}
//链表反转
struct RleNode* reverse(struct RleNode* head)
{
struct RleNode *prev = NULL, *current = NULL, *p = head->next;
if(p == NULL)
{
printf("空表");
}
while(p != NULL)
{
prev = current;
current = p;
p = p->next;
current->next = prev;
}
head->next = current;
return head;
}
//显示链表
void disp(struct RleNode* head)
{
struct RleNode* p= head->next;
if(p == NULL)
{
printf("空链表");
}
else
{
while(p->next != NULL)
{
printf("%d%c", p->count, p->ch);
p = p->next;
}
printf("%d%c\n", p->count, p->ch);
}
}
int main()
{
struct RleNode* head = (struct RleNode*)malloc(sizeof(struct RleNode));
char *str = "aaaaahhhhhhmmmmmmmuiiiiiiiaaaaaa";
printf("源字符串:%s\n",str);
head = encode(str);
printf("压缩后为:");
disp(head);
head = reverse(head);
printf("反转后:");
disp(head);
printf("解压后为:%s",decode(head));
return 0;
}