C语言单链表统计词频+选择排序
输入字符串(<25),统计词频并选择排序(升序)。
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
typedef struct node {
char data;
int count;//词频
struct node* next;
}node, * pnode;
pnode createList(char* q, int size);
void mergeList(pnode* m);//合并
void ptList(pnode head);//打印
void sortList(pnode* m);//选择排序
int main() {
int i, j, k, m, size;
pnode head;
char a[25] = { 0 };
scanf("%s", a);
size = strlen(a);//数组大小
head = createList(a, size);//尾插法
mergeList(&head);
sortList(&head);
ptList(head);
return 0;
}
pnode createList(char* q, int size) {
int i, j, k;
pnode head, p,m=NULL;
head = (pnode)malloc(sizeof(node));
if (head == NULL) { return NULL; }
head->next = NULL;
for (i = 0; i < size; i++) {//尾插法
p = (pnode)malloc(sizeof(node));
if (p == NULL) { return NULL; }
p->next = NULL;
p->data = q[i];
p->count = 1;
if (head->next == NULL) {
m=head->next = p;
}
else {
m->next = p;
m = m->next;
}
}
return head;
}
void mergeList(pnode* m) {//合并同类
int i, j;
pnode p, q, s = NULL;
p = q = (*m)->next;
if (q == NULL) {
printf("空链表");
return;
}
while (q != NULL&&q->next!=NULL) {//合并
while (p != NULL && p->next != NULL) {
if (p->next->data == q->data) {
s = p->next;
q->count++;
p->next = s->next;//p可能跳到NULL上
free(s);
}
if (p->next!=NULL&&p->next->data != q->data) {//bu xiang deng cai tiao
p = p->next;
}
}
q = q->next;
p = q;//复位
}
}
void ptList(pnode head) {
pnode p = head->next;
while (p != NULL) {
printf("%c %d ", p->data, p->count);
p = p->next;
}
}
void sortList(pnode* m) {//选择排序,升序
int i, j;
pnode p, q = NULL, s = NULL, t = NULL;
q = *m;//q记录位置,方便p回滚
p = (*m)->next;
if (p == NULL) {
printf("空链表");
return;
}
while (q != NULL && q->next != NULL) {
t= p = q->next;//p指向q
while (p != NULL && p->next != NULL) {//选择排序,每次最小值放q后面
if (p->next->count < t->next->count) {
t = p;//方便操作t->next
}
p = p->next;
}
if (t->next!=NULL&&t->next->count < q->next->count) {//考虑输入为abbbb情况
if (t->next->next != NULL) {
s = t->next;
t->next = s->next;
s->next = q->next;//先连后面
q->next = s;//再连前面
q = q->next;
}
else {//t为倒数第二个元素
t->next->next = q->next;
q->next = t->next;
t->next = NULL;
q = q->next;
}
}else {//t为尾元素
q = q->next;
}
}
}