//一个数组中有N个元素,找出其中重复次数最多的那个元素
#include
#include
int array[]={1,2,4,3,7,4,6,4,3,2,1,5,7,4,8,4,6,7,4,5,7,8,4,7,7,6,7,4,3,7};
typedef struct list_node
{
int element; //元素值
int count; //数组中出现次数
struct list_node* next;
}list_node;
list_node* head = NULL;
void insert(int val)
{
list_node* tmp = head;
list_node* pre = NULL;
if(tmp == NULL) //链表为空
{
head = (list_node*)malloc(sizeof(list_node));
head-> element = val;
head-> count = 1;
head-> next = NULL;
return;
}
while(tmp != NULL)
{
if(tmp -> element == val)
{
tmp -> count ++;
return;
}
else if(tmp -> element > val)
{
//产生一个新的链表节点
if(pre == NULL) //tmp为head
{
pre = (list_node*)malloc(sizeof(list_node));
pre-> element = val;
pre-> count = 1;
pre-> next = tmp;
head = pre;
return;
}
else
{
pre-> next = (list_node*)malloc(sizeof(list_node));
pre-> next-> element = val;
pre-> next-> count = 1;
pre-> next-> next = tmp;
return;
}
}
else
{
pre = tmp;
tmp = tmp -> next;
}
}
if(tmp == NULL) //加在链尾
{
pre-> next = (list_node*)malloc(sizeof(list_node));
pre-> element = val;
pre-> count = 1;
pre-> next-> next = NULL;
}
}
有一个问题 就是第一个节点在else
{
pre = tmp;
tmp = tmp -> next;
} 时接下来的pre->next后覆盖。掉,第一个节点的问题 。
阅读(1491) | 评论(0) | 转发(0) |