一个简单的数据结构问题 代码已写好 有点小问题 希望大佬帮我看下
要求:键盘输入英语单词的个数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;
}
最后的运行结果无法满足要求2.。。 求大佬帮助一下