main.c getword.h getword.c list.h list.c
main.c
#include
#include
#include "list.h"
#include "getword.h"
int main()
{
char s[20];//这里假设最大的单词长20,
//要更改长度同时也要更改list.c中struct 里面的长度
//这里假设单词只能是全英文加上数字,不能是其他的标点符号等等
//遇到不是字母和数字的直接结束输入
//要修改这个条件自己去getword.c里面修改
int maxcount;
struct node* head;
struct node* end;
struct node* p;
struct node* tmp;
head = malloc(sizeof(struct node));
if (head == NULL) {
printf("error: malloc error\n");
exit(1);
}
end = head;
while (getword(s)) {
struct node* f = find(s, head);
if (f == NULL)
insert(s, head, &end);
else
f->count++;
}
putchar('\n');
maxcount = 0;
for (p = head->next; p != NULL; p = p->next) {
printf("%s\t %d\n", p->str, p->count);
if (p->count > maxcount) {
tmp = p;
maxcount = p->count;
}
}
putchar('\n');
printf("appeared most: %s--%d times\n", tmp->str, tmp->count);
putchar('\n');
return 0;
}
getword.h
#ifndef _GETCH_H
#define _GETCH_H
#include
/*#define BUFSIZE 20
char buf[BUFSIZE];
int bufp = 0;
*/
int getword(char* );
//char getch(void );
//void ungetch(char );
#endif
getword.c
#include
#include
#include "getword.h"
#define BUFSIZE 20
char buf[BUFSIZE];
int bufp = 0;
char getch(void );
void ungetch(char );
int getword(char* s)
{
char c;
int i;
while ((s[0] = c = getch()) == ' ' || c == '\t'
|| c == '\n')
;
if (c == EOF || !isalnum(c))
return 0;
i = 0;
while (isalnum(s[++i] = c = getch()))
;
s[i] = '\0';
if (c != EOF) {
ungetch(c);
return 1;
}
else
return 0;
}
char getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(char c)
{
if (bufp >= BUFSIZE)
printf("ungetch: full\n");
else
buf[bufp++] = c;
}
list.h
#ifndef _LIST_H
#define _LIST_H
struct node {
char str[20];
int count;
struct node* next;
};
struct node* find(char*, struct node* );
void insert(char*, struct node*, struct node** );
//c语言没有引用,所以用指向指针的指针来对指向链表末尾的指针进行修改,
//保留指向链表末尾的指针的作用是不用每次都求链表末尾,看 list.c 文件注释掉的部分
#endif
list.c
#include
#include
#include
#include "list.h"
struct node* find(char* s, struct node* head)
{
struct node* p;
p = head->next;
while (p != NULL &&
(strcmp(s, p->str) != 0) ) {
p = p->next;
}
return p;
}
//对应注释掉的部分的参数类型是
//(char* s1, struct node* head)
//同时我们main函数也不许要end
void insert(char* s1, struct node* head, struct node** endp)
{
// struct node* p = head;
struct node* tmp;
/*
while (p->next != NULL)
p = p->next;
*/
tmp = malloc(sizeof(struct node));
if (tmp == NULL) {
printf("error: malloc error\n");
exit(1);
}
strcpy(tmp->str, s1);
tmp->count = 1;
tmp->next = NULL;
// p->next = tmp;
(*endp)->next = tmp;
*endp = tmp;
}