【问题描述】
输入若干个整数,统计出现次数最多的那个整数。如果出现最多的整数有两个以上,打印最早输入的那个整数。
【输入形式】
从标准输入读取输入。第一行只有一个数字N,代表整数的个数。以后的N行每行有一个整数。
【输出形式】
向标准输出打印出现次数最多的那个数字。
【输入样例】
6
11
0
-1
20
0
300
【输出样例】
0
【样例说明】
输入6个整数,其中出现次数最多的是0,共出现两次。
本题不准使用数学库函数。
用链表做了半天还是不行,那位能够解答这个问题??
#include<iostream>
#include<vector>
using namespace std;
int main()
{
vector<int>v1,v2;
int i;
cout<<"please enter the number of the int:"<<endl;
cin>>i;
cout<<"the number is:"<<endl;
for(int j=0;j<i;++j)
{
int k;
cin>>k;
v1.push_back(k);
}//end for
v2=v1;
for(int j=0;j<v2.size();++j)
{
int k=v2[j];
int count=0;
for(int a=0;a<v1.size();++a)
{
if(k==v1[a])
count++;
}
v2[j]=count;
count=0;
}//end for
int b;int max=0;//b为元素位置
for(int j=0;j<v2.size();++j)
{
if(v2[j]>max){
max=v2[j];
b=j;
}
}
int c=0;//个数相同的元素个数
for(int j=0;j<v2.size();++j)
{
if((v2[b]==v2[j])&&(v1[b]!=v1[j]))c+=1;
}
if(c==0)cout<<"个数最多的元素是 "<<v1[b]<<" 个数为 "<<v2[b]<<endl;
else
cout<<"没有最多的元素,第一歌输入的元素为 "<<v1[0]<<endl;
system("pause");
}
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NHASH 29989
#define MULT 31
#define MAXLEN 256
typedef struct node *nodeptr;
typedef struct node {
char *number;
int count;
nodeptr next;
} node;
nodeptr bin[NHASH];
unsigned int hash(char *p)
{
unsigned int h = 0;
for (; *p; p++) {
h = MULT * h + *p;
}
return h % NHASH;
}
void incword(char *s)
{
nodeptr p;
int h = hash(s);
for (p = bin[h]; p != NULL; p = p->next) {
if (strcmp(p->number, s) == 0) {
p->count++;
return;
}
}
if ((p = (nodeptr)malloc(sizeof(*p))) == NULL) {
fprintf(stderr, "malloc error");
exit(1);
}
p->count = 1;
if ((p->number = (char *)malloc(sizeof(char)*(strlen(s)+1))) == NULL) {
fprintf(stderr, "malloc error");
exit(1);
}
strcpy(p->number, s);
p->next = bin[h];
bin[h] = p;
}
int main(int argc, char *argv[])
{
int i, maxcount, m, sum;
char buf[MAXLEN];
nodeptr p;
FILE *fp;
for (i = 0; i < NHASH; i++) {
bin[i] = NULL;
}
if ((fp = fopen("data.txt", "r")) == NULL) {
fprintf(stderr, "cant open the file");
exit(1);
}
fscanf(fp, "%d", &sum);
for (i = 0; i < sum; i++) {
fscanf(fp, "%s", buf);
incword(buf);
}
for (i = 0, maxcount = 0; i < NHASH; i++) {
for (p = bin[i]; p != NULL; p = p->next) {
if (p->count > maxcount) {
maxcount = p->count;
m = atoi(p->number);
}
}
}
if (maxcount != 0) {
printf("%d\n", m);
}
fclose(fp);
return 0;
}
,创建一个链表应该可以搞定,
typedef struct node {
char *number;
int count;
nodeptr next;
} node
就是一个很好的例子,把输入的数字,做一个链表,然后根据链表输出就可以了哈
#include "iostream.h" //用结构实验的,在VC6.0中调试成功
struct str { //
int d; //输入的数
int numb; //以后面相同的次数
};
void main() {
int i,j,max;
int n;
cin>>n;
str *b=new str[n];
for(i=0;i<n;i++) {
cin>>b[i].d; //将输入的数存入结构str中,
b[i].numb=1;
for(j=0;j<i;j++) {
if(b[j].d==b[i].d) {//新输入的数如果和前面的数相等
b[j].numb++; //则前面的个数加1
}
}
}
max=0;
for(i=1;i<n;i++) { //标记出现次数最多的那个数
if(b[i].numb>b[max].numb)
max=i;
}
cout<<"出现最多次数的数是: b[max].d"<<endl;
delete []b;
}