求大神帮我看一下我的代码出现了什么问题,代码基本已经写好
问题:键盘输入英语单词的个数n及n个单词,编一程序,建立一个单向链表,实现: (1)如果单词重复出现,则只在链表上保留一个。
(2)除满足(1)的要求外。链表结点还应有一个计数域,记录该单词重复出现的次数,然后输出出现次数最多的前k(k<=n,需键盘输入)个单词。
我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
struct Node
{
char word[100];
int count;
struct Node *next;
};
struct Node* GetNode()
{
struct Node* p = (struct Node*) malloc(sizeof(struct Node));
p->next = 0;
p->count = 1;
memset(p->word, 0, 20);
return p;
}
void DestroyList(struct Node* head)
{
struct Node* p = head;
while (p)
{
struct Node* q = p;
p = p->next;
free(q);
}
}
struct Node* InsertNode(struct Node* head, char word[100])
{
struct Node* p = head;
while (p)
{
if ( strcmp(p->word, word)==0 )
{
++p->count;
return p;
}
p = p->next;
}
return p;
}
void DisplayList(struct Node* head)
{
while(head)
{
printf("%s ", head->word);
head = head->next;
}
}
void printListByK(struct Node *head, int k) {
int count = head->count;
if (k >= count) {
DisplayList(head);
} else {
struct Node *node = head->next;
for (int i = 0; i < k; i++) {
printf("word is %s, and count is %d", node->word, node->count);
node = node->next;
}
}
}
int main()
{
int num = 0;
scanf("%d", &num);
struct Node* head = GetNode();
struct Node* work = head;
for (int i=0; i<num; i++)
{
char word[100] = {0};
scanf("%s", word);
if ( InsertNode(head, word)==NULL )
{
struct Node* p = GetNode();
strcpy(p->word, word);
work->next = p;
work = work->next;
}
}
int k = 0;
while(k<=0||k>num)
{
printf("Please input k:");
scanf("%d",&k);
}
printListByK(head,k);
DisplayList(head->next);
DestroyList(head);
return 0;
}
运行结果
12
now us in now us us in in now please us us
Please input k:3
now us in please now us in please Program ended with exit code: 0