【发布时间】:2016-06-19 13:18:12
【问题描述】:
我正在尝试创建一个读取文本文件的程序 来自标准输入并打印按频率递减排序的单词及其频率。为此,我将单词存储在链表中,如果链表已经包含一个单词,则更新其频率。但是,我无法按单词的频率对链表进行排序。
我正在使用的struct 如下所示:
struct list {
char *word;
struct list *previous;
struct list *next;
int count;
};
所以我知道我应该将每个节点的count 值与其邻居的值进行比较,然后根据count 值切换它们的位置,但是我不知道如何保持函数循环直到它已排序。
我的代码是什么样子的:
struct list {
char *word;
struct list *previous;
struct list *next;
int count;
};
void list_add(struct list *l, char *word) {
struct list *current = l->previous;
struct list *prev;
int already_in_list = 0;
while (current != NULL) {
if (strcmp(current->word, word) == 0) {
current->count++;
already_in_list = 1;
// Compare new frequency with elements higher
// up in the list and sort*/
**How do I do this?**
}
prev = current;
current = current->next;
}
if (already_in_list != 1) list_add_new(l, word);
}
当前输出为:
word: bye count: 1
word: is count: 1
word: my count: 1
word: hello count: 6
word: world count: 2
word: name count: 1
我想要的输出:
word: hello count: 6
word: world count: 2
word: name count: 1
word: bye count: 1
word: is count: 1
word: my count: 1
【问题讨论】:
-
根据您的预期输出:是否应该有任何相同出现的单词的顺序?现在好像没有……
-
不,为什么会有?
-
我在问是否应该以某种方式对同等出现的词进行排序,如果是,您将如何排序;按字母顺序、未修改、随机放置等。
-
我并不关心频率相同的单词是如何排序的。
-
对链表进行排序的最佳方法:1) 创建指向链表元素的指针数组,2) 使用
qsort库函数对指针进行排序,3) 重新创建链表从已排序的指针数组中列出。
标签: c sorting linked-list