数据结构实验:哈希表

题目描述

 在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个。

输入

 单组数据,第一行数字n(1<=n<=100000)。
接下来有n个数字,每个数字不超过100000000

输出

 出现次数最多的数字和次数。

示例输入

3
1 1 2

示例输出

1 2
#include<stdio.h>
#include<stdlib.h>
struct node {
    int data;
    int ans;
    struct node *next;
}*head[100010];
int main() {
    int i, n, x, y, shu = -1, ci = -1;
    struct node *p, *q, *r;
    for(i=0; i<100000; i++) {
        head[i] = (struct node *)malloc(sizeof(struct node));
        head[i]->next = NULL;
    }
    scanf("%d", &n);
    for(i=0; i<n; i++) {
        scanf("%d", &x);
        y = x % 100000;
        p = head[y]->next;
        q = head[y];
        while(p != NULL) {
            if(p->data == x) {
                p->ans++;
                if(ci < p->ans) {
                    shu = p->data;
                    ci = p->ans;
                }
                else if(ci == p->ans) {
                    if(shu > p->data)
                        shu = p->data;
                }
                break;
            }
            q = p;
            p = p->next;
        }
        if(p == NULL) {
            r = (struct node *)malloc(sizeof(struct node));
            r->data = x;
            r->ans = 1;
            if(ci < r->ans) {
                shu = r->data;
                ci = r->ans;
                }
            else if(ci == r->ans) {
                if(shu > r->data)
                    shu = r->data;
            }
            q->next = r;
            r->next = NULL;
        }
    }
    printf("%d %d\n", shu, ci);
    return 0;
}