链地址法+动态开辟内存 hash
2015-05-29 22:38
471 查看
链地址法 (一)
自我感觉链地址法是hash的最简单易懂的方法,于是就在课下实现了一下
它的特点是能够较直观的解决冲突问题
但是同样,它也有缺点,那就是每次查询时都要遍历某个头结点后面的所有结点
如图示
因此优化方法是
1:尽可能的使用素数作为mod的对象
2:mod的对象足够大
这样可以使数字排列的更散乱,以减少冲突
要求输入n个数,查询m次,
代码如下
自我感觉链地址法是hash的最简单易懂的方法,于是就在课下实现了一下
它的特点是能够较直观的解决冲突问题
但是同样,它也有缺点,那就是每次查询时都要遍历某个头结点后面的所有结点
如图示
因此优化方法是
1:尽可能的使用素数作为mod的对象
2:mod的对象足够大
这样可以使数字排列的更散乱,以减少冲突
要求输入n个数,查询m次,
代码如下
<strong>#include<stdio.h> #include<string.h> #include<stdlib.h> using namespace std; struct node { int x; node *next; // node() // { // next=NULL; // } }; int n,m; const int mod=99997; node *str[mod]; void hasha(int a) { int b=a; a=a%mod; node *q=str[a]; while(q->next) { q=q -> next; }//new (node); node *p=(node*) malloc (sizeof(node)); p->next=NULL; p->x=b; q->next=p; return; } int main() { for(int i=0; i<mod; i++) { // str[i]=new(node); str[i]=(node*) malloc (sizeof(node)); str[i]->next=NULL; } node *p=NULL; int aa; scanf("%d%d",&n,&m); while(n--)//输入n个数 { scanf("%d",&aa); hasha(aa); } while(m--)//查询n次 { scanf("%d",&aa); int bb=aa; aa=aa%mod; p=str[aa]; int flog=0; while(p->next) { p=p->next; if(bb==p->x) { flog=1; break; } } if( flog == 0 ) printf("NO\n"); else printf("YES\n"); } } </strong>
相关文章推荐
- PHP & HTML学习
- 疯狂Java学习笔记(60)----------8张图理解Java
- WEBFORM--第三讲(简单控件)
- 虚拟机的三种网络模式
- 现在
- (6) 如何用Apache POI操作Excel文件-----POI-3.10的一个和注解(comment)相关的另外一个bug
- 疯狂Java学习笔记(59)-----------50道Java线程面试题
- Android 开发工具类 25_getJSON
- 3.1-2
- 【C++】基于特征向量的KNN分类算法
- ClassLoader 详解及用途
- IT人生思考
- Java NIO原理图文分析及代码实现
- HDU 3488 — Tour 费用流/KM算法
- Windows程序设计(消息机制)
- 黑马程序员-数据类型、变量作用域和数据结构的学习笔记
- hdu 1203 dp背包问题
- 对C++中迭代器的分类的认识
- Oracle学习(4):分组函数
- 线程池