【正确答案】(1)
#define KEYTYPE int /*查找表的结点类型定义*/
#define MAXSIZE 100
typedef struct
{KEYTYPE key;
}SEQLIST;
int seq_search(KEYTYPE k,SEQLIST*st,int n) /*顺序表上查找元素算法*/
{ int j;
j=n; /*顺序表元素个数*/
st[0].key:k; /*st.r[0]单元作为监视哨*/
while(st[j].key!=k) /*顺序表从后向前查找*/
j--;
return j;
}
main()
{ SEQLIST a[MAXSIZE];
int i,k,n;
scanf("/%d",&n);
for(i=1;i<=n;i++)
scanf("/%d",&a[i].key);
printf("输入待查元素关键字:");
scanf("/%d",&i);
k=seq_search(i,a,n);
if(k==0)
printf("表中待查元素不存在");
else
printf("表中待查元素的位置/%d",k);
}
(2)
#define KEYTYPE int /*查找表的结点类型定义*/
#define MAXSIZE 100
typedef struct
{KEYTYPE key;
}SEQLIST;
int bsearch(SEQLIST*st,KEYTYPE k,int n) /*有序表上二分查找非递归算法*/
{ int low,high,mid;
low=1;high=n;
while(low<=high)
{ mid=(low+high)/2;
if(st[mid].key==k)
return mid;
else if(st[mid].key>k)
high=mid-1;
else
low=mid+1;
}
return 0;
}
main()
{ SEQLIST a[MAXSIZE];
int i,k,n;
scanf("/%d",&n);
for(i=1;i<=n;i++)
scanf("/%d",&a[i].key);
printf("输入待查元素关键字:");
scanf("/%d",&i);
k=bsearch(a,i,n);
if(k==0)
printf("表中待查元素不存在");
else
printf("表中待查元素的位置/%d",k);
}
(3)
#define NULL'\0'
#define m 13
typedef struct node
{ int key;
struct node*next;
}CHAINHASH;
void creat_chain_hash(CHAINHASH *HTC[])
{ CHAINHASH *p;
int i,d;
scanf("/%d",&i);
while(i!=0)
{
d=i/%13;
p=(CHAINHASH*)malloc(sizeof(CHAINHASH));
p->next=HTC[d];
p->key=i;
HTC[d]=p;
scanf("/%d",&i);}
}
void print_chain_hash(CHAINHASH *HTC[])
{ int i;
CHAINHASH *p;
for(i=0;i<13;i++)
{ if(HTC[i]==NULL)printf("/%3d |"\n",i);
else{p=HTC[i];
printf("/%3d|->",i);
while(p!=NULL)
{printf("/%5d->",p->key);p=p->next; )
printf("^\n");
}
}
}
CHAINHASH *search_chain_hash(CHAINHASH *HTC[], int k)
{ CHAINHASH*p;
int d;
d=k/%13:
p=HTC[d];
while(p!=NULL&&p->key!=k)
p=p->next;
return p;
}
main()
{ CHAINHASH *HTC[m];
int i;
CHAINHASH*p;
printf("\nplease input data\n\n");
for(i=0;i<m; i++)
HTC[i]=NULL;
printf("biao\n");
creat_chain_hash(HTC);
print_chain hash(HTC);
printf("\ninput i:");
scanf("/%d",&i);
p=search_chain_hash(HTC,i);
if(p==NULL)printf("no found\n\n");
else printf("exist,/%d\n",p->key);
}
【答案解析】