#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <math.h>
#include <time.h>
#include <Windows.h>
#define MAXSIZE 20
struct seqList
{
int data[MAXSIZE];
int size;
};
//初始化
void init_SeqList1(struct seqList* list)
{
for (int i = 0; i < MAXSIZE; i++)
{
list->data[i] = 0;
}
list->size = 0;
}
//创建线性表
void create_SeqList1(struct seqList* list)
{
int len;
printf("请输入要创建的顺序表的长度:");
scanf_s("%d", &len);
for (int i = 0; i < len; i++)
{
scanf_s("%d", &list->data[i]);
list->size++;
}
}
void bubbleSort_SeqList1(struct seqList* list)
{
for (int i = 0; i < list->size - 1; i++)
{
for (int j = 0; j < list->size - i - 1; j++)
{
if (list->data[j] > list->data[j + 1])
{
int temp = list->data[j];
list->data[j] = list->data[j + 1];
list->data[j + 1] = temp;
}
}
}
}
void findMainValue(struct seqList* list)
{
int x, flag = 0;
int* arr = malloc(list->size * sizeof(int));
for (int i = 0; i < list->size; i++)
{
arr[i] = 0;
}
//统计每个元素出现的次数,将当前元素当成数组下标来使用
for (int i = 0; i < list->size; i++)
{
arr[list->data[i]]++;
}
//以顺序表中的元素为下标在arr数组中找对应下标中存储的数据是否大于顺序表长度的一半,若是则该数为主元元素
for (int i = 0; i < list->size; i++)
{
if (arr[list->data[i]] > list->size / 2)
{
x = list->data[i];
flag = 1;
break;
}
}
if(flag==1)
printf("该顺序表中存在主元素,主元素为:%d\n", x);
else
printf("%d\n", -1);
}
void printf_SeqList1(struct seqList* list)
{
for (int i = 0; i < list->size; i++)
{
printf("%d ", list->data[i]);
}
printf("\n");
}
int main(void)
{
struct seqList list;
init_SeqList1(&list);
create_SeqList1(&list);
//bubbleSort_SeqList1(&list);
printf("初始顺序表为:\n");
printf_SeqList1(&list);
findMainValue(&list);
system("pause");
return EXIT_SUCCESS;
}