在C语言中,如何统计一维数组中重复频率最多次的元素,(数组中可能存在多组相同元素),并将其输出。

2024-12-16 03:10:36
推荐回答(1个)
回答1:

#include
#include

struct VALUE_INFO
{
int nValue;
int nCount;
struct VALUE_INFO *pNextInfo;
};

void main()
{
unsigned short arr[] = {1, 2, 2, 4, 5, 6, 6, 6, 6, 7, 8, 8, 9};
int MAX_SIZE = sizeof(arr) / sizeof(short);
struct VALUE_INFO *pHeadInfo = NULL, *pEndInfo = NULL, *pTempInfo;
int i;
int nMaxCount = -1;
short sLastValue;
for (i = 0; i < MAX_SIZE; i++)
{
if (pHeadInfo == NULL)
{
pHeadInfo = (struct VALUE_INFO*)malloc(sizeof(struct VALUE_INFO));
pHeadInfo->nValue = arr[i];
pHeadInfo->nCount = 1;
pHeadInfo->pNextInfo = NULL;
pEndInfo = pHeadInfo;
sLastValue = arr[i];
continue;
}
if (sLastValue != arr[i])
{
pTempInfo = (struct VALUE_INFO*)malloc(sizeof(struct VALUE_INFO));
pTempInfo->nValue = arr[i];
pTempInfo->nCount = 1;
pTempInfo->pNextInfo = NULL;
pEndInfo->pNextInfo = pTempInfo;
pEndInfo = pTempInfo;
sLastValue = arr[i];
}
else
{
pTempInfo->nCount++;
}
}

while (pHeadInfo)
{
if (pHeadInfo->nCount > nMaxCount)
{
pTempInfo = pHeadInfo;
nMaxCount = pHeadInfo->nCount;
}
pHeadInfo = pHeadInfo->pNextInfo;
}

printf("Max count = %d, value = %d\n", pTempInfo->nCount, pTempInfo->nValue);
system("PAUSE");
}