| 网站首页 | 业界新闻 | 小组 | 威客 | 人才 | 下载频道 | 博客 | 代码贴 | 在线编程 | 编程论坛
欢迎加入我们,一同切磋技术
用户名:   
 
密 码:  
共有 979 人关注过本帖
标题:求大神帮我看一下我的代码出现了什么问题,代码基本已经写好
只看楼主 加入收藏
数据结构难学
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2018-9-22
收藏
 问题点数:0 回复次数:1 
求大神帮我看一下我的代码出现了什么问题,代码基本已经写好
问题:键盘输入英语单词的个数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
搜索更多相关主题的帖子: struct Node word next head 
2018-09-22 11:29
数据结构难学
Rank: 1
等 级:新手上路
帖 子:3
专家分:0
注 册:2018-9-22
收藏
得分:0 
最后的结果无法满足要求2.。。
2018-09-22 11:59
快速回复:求大神帮我看一下我的代码出现了什么问题,代码基本已经写好
数据加载中...
 
   



关于我们 | 广告合作 | 编程中国 | 清除Cookies | TOP | 手机版

编程中国 版权所有,并保留所有权利。
Powered by Discuz, Processed in 0.014666 second(s), 8 queries.
Copyright©2004-2024, BCCN.NET, All Rights Reserved