HDOJ 1004:统计气球数

本文详细介绍了如何通过链表结构解决HDU评测平台给出的多色计数问题,包括实现思路、程序代码及具体操作流程。通过接收一系列颜色数据并统计最频繁出现的颜色,为编程爱好者提供了解决此类问题的实用指南。

题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1004

一、题目要求

输入:给定一个数字和一组颜色数据,数字是这组颜色数据的数量。当输入的数字为0时结束。

输出:对于每一组给定的颜色数据,统计其中出现频率最高的颜色。

二、实现思路

用链表统计颜色数,每发现一个新颜色都插入一个新结点。接收完所有数据后,遍历链表可以找出统计数量最多的颜色,该颜色即为所求。

三、程序代码

#include<iostream>

using namespace std;

//结构:结点
struct Node
{
    string color; //颜色名
    int count;    //接收到该颜色的数量
    Node *next;   //下个结点指针
};

int main()
{
    int count;
    while(cin >> count)
    {
        if(count == 0)
        {
            break;
        }
        
        string color; //接收输入
        Node *head = NULL, *pointer;
        while(count--)
        {
            cin >> color;

            //首结点为空则插入首结点
            if(head == NULL)
            {
                head = new Node();
                head -> color = color;
                head -> count = 1;
                head -> next = NULL;
            }
            else //否则遍历整个链表
            {
                pointer = head;
                while(true)
                {
                    //链表中已经存在该颜色,则让其数目自增1,退出循环
                    if(pointer -> color == color)
                    {
                        pointer -> count++;
                        break;
                    }

                    //未遍历到尾结点,则继续遍历
                    if(pointer -> next != NULL)
                    {
                        pointer = pointer -> next;
                        continue;
                    }
                    else //遍历到尾结点,则在最后新增一个该色的结点
                    {
                        pointer -> next = new Node();
                        pointer -> next -> color = color;
                        pointer -> next -> count = 1;
                        pointer -> next -> next = NULL;
                    }
                }
            }
        }
        
        //统计数量最多的结点
        string sMax = "";
        int iCount = 0;
        pointer = head;
        while(pointer != NULL)
        {
            if(pointer -> count > iCount)
            {
                sMax = pointer -> color;
                iCount = pointer -> count;
            }
            pointer = pointer -> next;
        }

        //输出数量最多的结点颜色名
        cout  << sMax << endl;
    }

    return 0;
}

END

转载于:https://my.oschina.net/Tsybius2014/blog/299482

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值