写一个单词收集统计程序,标准输入若干单词,输入特定字符串("count-end"不参与统计)结束统计,并打印结果。
例如:
依次输入:hello book look hello look and count-end
打印结果:
hello出现2次
book出现1次
look出现2次
and出现一次
要求用链表实现,同时注意编码规范。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node {
char word[20];
struct Node* next;
};
void add_word(struct Node** head, char* word) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
strcpy(new_node->word, word);
new_node->next = *head;
*head = new_node;
}
void print_words(struct Node* head) {
while (head != NULL) {
printf("%s\n", head->word);
head = head->next;
}
}
int main() {
struct Node* head = NULL;
char word[20];
while (scanf("%s", word) != EOF) {
add_word(&head, word);
}
print_words(head);
return 0;
}
直接上代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20
struct node {
char word[MAX_LEN];
int count;
struct node *next;
};
typedef struct node Node;
Node *head = NULL;
Node *search(char *word) {
Node *p = head;
while (p != NULL) {
if (strcmp(p->word, word) == 0) {
return p;
}
p = p->next;
}
return NULL;
}
void insert(char *word) {
Node *p = search(word);
if (p == NULL) {
Node *new_node = (Node *)malloc(sizeof(Node));
strcpy(new_node->word, word);
new_node->count = 1;
new_node->next = head;
head = new_node;
} else {
p->count++;
}
}
int main() {
char word[MAX_LEN];
while (scanf("%s", word) != EOF) {
if (strcmp(word, "count-end") == 0) {
break;
}
insert(word);
}
Node *p = head;
while (p != NULL) {
printf("%s出现了%d次\n", p->word, p->count);
p = p->next;
}
return 0;
}