题目地址:http://acm.hdu.edu.cn/showproblem.php?pid=1004php
1、题目要求ios
输入:给定一个数字和一组颜色数据,数字是这组颜色数据的数量。当输入的数字为0时结束。spa
输出:对于每一组给定的颜色数据,统计其中出现频率最高的颜色。指针
2、实现思路code
用链表统计颜色数,每发现一个新颜色都插入一个新结点。接收完全部数据后,遍历链表能够找出统计数量最多的颜色,该颜色即为所求。ci
3、程序代码get
#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; }
ENDstring