Chinaunix首页 | 论坛 | 博客
  • 博客访问: 532751
  • 博文数量: 150
  • 博客积分: 5010
  • 博客等级: 大校
  • 技术积分: 1861
  • 用 户 组: 普通用户
  • 注册时间: 2008-03-17 00:19
文章分类

全部博文(150)

文章存档

2011年(1)

2009年(14)

2008年(135)

我的朋友

分类: 系统运维

2008-07-08 13:12:54

//一个数组中有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后覆盖。掉,第一个节点的问题 。
阅读(1456) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~