【发布时间】:2016-12-21 23:33:12
【问题描述】:
好的,我现在有什么,检查单词的计数。但我无法按字母顺序对单词进行排序。
我宁愿这样做,然后只计算它们的数量。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef struct node *node_ptr;
typedef struct node {
int count;
char *word;
node_ptr next;
} node_t;
char *words[] = { "hello", "goodbye", "sometimes", "others", "hello", "others", NULL };
node_ptr new_node() {
node_ptr aNode;
aNode = (node_ptr)(malloc(sizeof(node_t)));
if (aNode) {
aNode->next = (node_ptr)NULL;
aNode->word = (char *)NULL;
aNode->count = 0;
}
return aNode;
}
node_ptr add_word(char *word, node_ptr theList) {
node_ptr currPtr, lastPtr, newPtr;
int result;
int found = 0;
currPtr = theList;
lastPtr = NULL;
printf("Checking word:%s\n", word);
if (!currPtr) {
newPtr = new_node();
if (!newPtr) {
fprintf(stderr, "Fatal Error. Memory alloc error\n");
exit(1);
}
newPtr->word = word;
newPtr->next = currPtr;
newPtr->count = 1;
found = 1;
theList = newPtr;
}
while (currPtr && !found) {
result = strcmp(currPtr->word, word);
if (result == 0) {
currPtr->count += 1;
found = 1;
} else
if (result>0) {
newPtr = new_node();
if (!newPtr) {
fprintf(stderr, "Fatal Error. Memory alloc error\n");
exit(1);
}
newPtr->word = word;
newPtr->next = currPtr;
newPtr->count = 1;
if (lastPtr) {
lastPtr->next = newPtr;
} else {
theList = newPtr;
}
found = 1;
} else {
lastPtr = currPtr;
currPtr = currPtr->next;
}
}
if ((!found) && lastPtr) {
newPtr = new_node();
if (!newPtr) {
fprintf(stderr, "Fatal Error. Memory alloc error\n");
exit(1);
}
newPtr->word = word;
newPtr->next = (node_ptr)NULL;
newPtr->count = 1;
lastPtr->next = newPtr;
found = 1;
}
return theList;
}
void printList(node_ptr theList) {
node_ptr currPtr = theList;
while (currPtr) {
printf("word: %s\n", currPtr->word);
printf("count: %d\n", currPtr->count);
printf("---\n");
currPtr = currPtr->next;
}
}
int main() {
char **w = words;
node_ptr theList = (node_ptr)NULL;
printf("Start\n");
while (*w) {
theList = add_word(*w, theList);
w++;
}
printList(theList);
printf("OK!\n");
return 0;
}
我还想从一个文件中读取,而不是从一个单词数组中读取。
FILE *fp;
fp = fopen("some.txt", "w");
如何使用我创建的结构从文件中读取数据,然后对其进行排序?
【问题讨论】:
-
typedef 指针是个坏习惯:
typedef struct node *node_ptr;隐藏指针并不能让它们更容易理解或处理,恰恰相反,它会混淆你的代码。 -
在
add_word(),newPtr->word = word;是一个问题。代码可能需要添加字符串的副本。 -
很抱歉给您带来了困惑。我想同时做@WeatherVane .. 我想从文件中读取单词并按字母顺序排序!
-
了解
qsort
标签: c file sorting linked-list