各単語の出現を降順で並べ替えるにはどうすればよいですか?C並べ替えの問題
私の現在のコードは次のとおりです。
#include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <ctype.h>
#include <string.h>
#define WORDLEN 50
typedef struct node_struct NODE;
struct node_struct {
char *word;
int count;
NODE *next;
};
/*compare and adds words to the list*/
NODE *new_node(char *word, NODE *head) {
NODE *p = head;
char *s;
if (p == NULL) {
p = (NODE*)malloc(sizeof(NODE));
s = (char*)malloc(sizeof(strlen(word) + 1));
strcpy(s, word);
p->word = s;
p->count = 1;
p->next = head;
return p;
}
for (; p->next != NULL && strcmp(p->word, word) != 0; p = p->next);
if (strcmp(p->word, word) == 0) {
p->count += 1;
return head;
}else{
p->next = (NODE*)malloc(sizeof(NODE));
p = p->next;
s = (char*)malloc(sizeof(strlen(word) + 1));
strcpy(s, word);
p->count = 1;
p->word = s;
p->next = NULL;
return head;
}
}
/*gets words*/
char *getword(char *w, int n)
{
int i = 0;
int c;
if (n <= 0 || feof(stdin))
return NULL;
c = getchar();
while (c != EOF && ! isalpha(c)) {
c = getchar();
}
if (c == EOF)
return NULL;
while (isalpha(c)) {
if (i < n - 1) {
w[i] = toupper(c);
i++;
}
c = getchar();
}
w[i] = '\0';
return w;
}
/*print*/
void print(NODE *p) {
for (; p != NULL; p = p->next) {
printf("%s %d\n",p->word, p->count);
}
printf("\n");
}
int main()
{
char w[WORDLEN];
NODE *p = NULL;
int i;
while (getword(w, WORDLEN) != NULL) {
p = new_node(w, p);
}
print(p);
return 0;
}
? – berkay
バブルソートを試みたことがありますが、ポインタで動作させるのが難しいと感じています。 – bob
http://stackoverflow.com/questions/4365025/insertion-sort-in-c-using-linked-list/4367133#4367133 – Christoph