#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define max 15
/*1、输入10个一百以内的数,用x%15作为哈希函数,
采用线性探测法作为冲突处理方法,将数据逐个放入大小为15的数组中。
输出散列表的存储示意图(第一行输出下标,第二行输出横线,第三行输出数据)。
并对其进行查找,输出(找到、找不到时的)查找次数。
2、输入10个一百以内的数,用x%15作为哈希函数,用拉链法作为存储结构。
输出散列表的存储示意图。并对其进行查找,输出(找到、找不到时的)查找次数。
3、编程实现直接插入排序。*/
typedef struct kk
{
int data;
struct kk * next;
}node;
typedef struct aa
{
node * hash[max];
}list;
void inserthash1(int x,int a[])
{
int i;
i=x%max;
while(a[i]!=0)
i=(i+1)%max;
a[i]=x;
}
list * inserthash2(int x,list *L)
{
int i;
node *p,*s;
p=(node*)malloc(sizeof(node));
i=x%max;
p=L->hash[i];
while(p->next)
{
p=p->next;
}
s=(node*)malloc(sizeof(node));
s->data=x;
p->next=s;
s->next=NULL;
return L;
}
list * createhash()
{
list *L;
int i;
for(i=0;i<max;i++)
{
L->hash[i]=(node*)malloc(sizeof(node));
L->hash[i]->data=i;
L->hash[i]->next=NULL;
}
return L;
}
void print2(list *L)
{
int i;
node *q;
for(i=0;i<max;i++)
{
q=(node*)malloc(sizeof(node));
for(q=L->hash[i];q!=NULL;q=q->next)
printf("%4d",q->data);
printf("\n");
}
}
void print1(int a[])
{
int i;
for(i=0;i<max;i++)
printf("%4d",i);printf("\n");
for(i=0;i<max;i++)
printf("----");printf("\n");
for(i=0;i<max;i++)
printf("%4d",a[i]);printf("\n");
}
void find1(int a[],int x)
{
int i,s=0;
i=x%max;
while(a[i]!=x && a[i]!=0)
{
i=(i+1)%max; s++;
}
if(a[i]==0)
{
s++;
printf("error,s:%d\n",s);
}
if(a[i]==x)
{
s++;
printf("%3d",s);
}
}
void insertsort(int a[],int len)
{
int i,j,t;
for(i=1;i<len;i++)
{
t=a[i]; j=i-1;
while(j>=0 && a[j]>t)
{
a[j+1]=a[j]; j--;
}
a[j+1]=t;
}
}
void sort(int a[],int len)
{
int i,j,k,t;
for(i=0;i<len;i++)
{
for(j=i-1;j>=0;j--)
if(a[j]<a[i]) break;
if(j!=i-1)
{
t=a[i];
for(k=i-1;k>j;k--)
a[k+1]=a[k];
a[k+1]=t;
}
}
}
void display(int a[],int len)
{
int i;
for(i=0;i<len;i++)
printf("%d ",a[i]);
}
int main()
{
int a[max];
int b[10]={2,4,1,6,7,8,9,3,10,5,6};
int x,y,z,i;
for(i=0;i<max;i++)
a[i]=0;
list *L;
L=(list*)malloc(sizeof(list));
printf("input:\n");//1 30 16 15 33 55 44 3 2 17 -1
scanf("%d",&x);
while(x!=-1)
{
inserthash1(x,a);
scanf("%d",&x);
}
print1(a);
printf("\ninput:\n");
scanf("%d",&y);
while(y!=-1)
{
find1(a,y);
scanf("%d",&y);
}
printf("\n");
printf("input:\n");
L=createhash();
scanf("%d",&z);
while(z!=-1)
{
L=inserthash2(z,L);
scanf("%d",&z);
}
print2(L);
insertsort(b,10);
printf("\nsort: "); display(b,10);
}
输入数据:1 30 16 15 33 55 44 3 2 17 -1
运行结果如下