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

被折叠的 条评论
为什么被折叠?



