不用char数组,不给限定字符串长度实现结果


#include 
#include 
#include 

#define MAX 20

struct node {
    char word[MAX];
    int count;
    struct node *next;
};

typedef struct node nodes;
nodes *head = NULL;

nodes *search(char *word) {
    nodes *p = head;
    while (p != NULL) {
        if (strcmp(p->word, word) == 0) {
        return p;
        }
    p = p->next;
    }
    return NULL;
}

void insert(char *word) {
    nodes *p = search(word);
    if (p == NULL) {
        nodes *new_node = (nodes *)malloc(sizeof(nodes));
        strcpy(new_node->word, word);
        new_node->count = 1;
        new_node->next = head;
        head = new_node;
    } else {
        p->count++;
    }
}

int main() {
    char word[MAX];
    while (scanf("%s", word) != EOF) {
        if (strcmp(word, "count-end") == 0) {
        break;
        }
        insert(word);
    }

nodes *p = head;
while (p != NULL) {
    printf("%s出现了%d次\n", p->word, p->count);
    p = p->next;
    }
    return 0;
}
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
 
struct node {
    char *word;
    int count;
    struct node *next;
};
 
typedef struct node nodes;
nodes *head = NULL;
 
nodes *search(char *word) {
    nodes *p = head;
    while (p != NULL) {
        if (strcmp(p->word, word) == 0) {
        return p;
        }
    p = p->next;
    }
    return NULL;
}
 
void insert(char *word) {
    nodes *p = search(word);
    if (p == NULL) {
        nodes *new_node = (nodes *)malloc(sizeof(nodes));
        int len = strlen(word);
        new_node->word = (char*)malloc(sizeof(char)*len);
        strcpy(new_node->word, word);
        new_node->count = 1;
        new_node->next = head;
        head = new_node;
    } else {
        p->count++;
    }
}
 
int main() {
    char word[MAX];
    while (scanf("%s", word) != EOF) {
        if (strcmp(word, "count-end") == 0) {
        break;
        }
        insert(word);
    }
 
nodes *p = head;
while (p != NULL) {
    printf("%s出现了%d次\n", p->word, p->count);
    p = p->next;
    }
    return 0;
}

max限定太小了的话,你把它改2000不就足够长了吗
不用char数组你就不能用%s来获取,而必须循环%c来读取,然后存个链表