注册 登录
编程论坛 C++教室

一个简单的数据结构问题 代码已写好 有点小问题 希望大佬帮我看下

数据结构难学 发布于 2018-09-22 11:34, 1185 次点击
要求:键盘输入英语单词的个数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.。。 求大佬帮助一下

2 回复
#2
Jonny02012018-09-23 10:25
前面没看出哪里不对
估计是 输出出现次数最多的前k(k<=n,需键盘输入)个单词 这里不对
STL 里的 forward_list 的排序是额外写的
所以对于单链表的排序你也要额外写一个函数才行
#3
rjsp2018-09-25 08:51
你同一个问题,既在C板块贴,又在C++板块贴。
C 和 C++ 是两门不同的编程语言。

1