HDOJ 1004:統計氣球數

題目地址: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

相關文章
相關標籤/搜索