sdut 数据结构实验:哈希表(链表型)

数据结构实验:哈希表
Time Limit: 1000 ms Memory Limit: 65536 KiB

Problem Description
在n个数中,找出出现次数最多那个数字,并且输出出现的次数。如果有多个结果,输出数字最小的那一个。
Input
单组数据,第一行数字n(1<=n<=100000)。
接下来有n个数字,每个数字不超过100000000
Output
出现次数最多的数字和次数。
Sample Input
3
1 1 2
Sample Output
1 2

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
struct node
{
    int data;
    int num;
    struct node *next;
}*h[100010],*q,*t,*p;
int main()
{
    int m,n;
    int i,max=0,maxs=0;
    for(i=0; i<100010; i++)
    {
        h[i]=(struct node*)malloc(sizeof(struct node)); //弄一个头结点
        h[i]->next=NULL;
    }
    scanf("%d",&n);
    for(i=0; i<n; i++)
    {
        scanf("%d",&m);
        int w;
        w=m%100010;          //取余
        q=h[w];
        p=h[w]->next;
        while(p!=NULL)
        {
            if(p->data==m)
            {
                p->num++;
                if(p->num>maxs)
                {
                    maxs=p->num;
                    max=p->data;
                }
                else if(p->num==maxs)
                {
                    if(p->data<max)
                    {
                        max=p->data;
                    }
                }
                break;      //如果有相等的直接跳出,并且下面那个if也不会执行
            }
            q=q->next;
            p=p->next;
        }
        if(p==NULL)
        {
            t=(struct node*)malloc(sizeof(struct node));  //申请新的空间
            t->next=NULL;
            t->data=m;
            t->num=1;    //在链表后面插入新的,置为1;
            q->next=t;
            p=t;
            if(p->num>maxs)
            {
                maxs=p->num;
                max=p->data;
            }
            else if(p->num==maxs)
            {
                if(p->data<max)
                    max=p->data;
            }
        }
    }
    printf("%d %d\n",max,maxs);
    return 0;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值