请高手帮我解答关于单链表的创建和稀疏矩阵的哈希解法的问题
第一个问题:
向单链表插入新元素的sls_store中的参数start.last为何要定义成二级间址的指针,直接定义成一级间址的指针不也可以吗?
创立单链表时的函数如下:
struct address {
char name[40];
char street[40];
char city[20];
struct address *next; /* link to next address */
}info;
/*store in sorted order*/
void sls_store(struct address *i,/*new element to store*/
struct address **start,/*start of list*/
struct address **last) /*end of list*/
{
struct address *old,*p;
p=*start;
if(!*last){/*first element in list */
i->next=Null;
*last=i;
*start=i;
return;
}
old=null;
while(p){
if(strcmp(p->name,i->name)<0{
old=p;
p=p->next;
}
else{
if(old){/*goes in middle */
old->next=i;
i->next=p;
return;
}
i->next=p; /*new first element */
*start=i;
return;
}
}
(*last)->next=i; /*put on end*/
i->next=null;
*last=i;
}
第二个问题:
对于用散列(hashing)方法处理稀疏数组(矩阵)问题:
我觉得在函数store 中的if 条件中只应该有primary[h].index==-1这一个条件不应该有primary[h].index==loc这一个条件:
具体函数如下:
结构数组,主(primary)数组如下:
#define MAX 260
struct htype{
int index; /*logical index */
int val; /* actual value of the array element */
struct htype *next /* pointer to next value with same hash */
}primary[MAX];
/* Initialize the hash array */
void init(void)
{
register int i;
for(i=0;i<MAX;i++){
primary[i].index=-1;
primary[i].next=NULL; /*null chain */
primary[i].val=0;
}
}
/*Compute hash and store value */
void store(char *cell_name,int v)
{
int h,loc;
struct htype *p;
/*produce the hash value */
loc=*cell_name -'A'; /*colume*/
loc+=(atoi(&cell_name[1]-1)*26; /*rows*width + columns */
h=loc/10; /*hash*/
/*store in the location unless full or store there if logical indexes agree -i.e.,update. */
/*我就是在下面这个IF条件中有问题,我觉得只要第一个条件就可以了,不需要再或一个条件*/
if(primary[h].index==-1||primary[h].index==loc){
primary[h].index=locp;
primary[h].val=v;
return;
}
/*otherwise,create or add to collision list */
p=(struct htype *)malloc(sizeof(struct htype));
if(!p){
printf("Out of Memory \n");
return;
}
p->index=loc;
p->val=v;
slstore(p,&primary[h]);
}
/*add elements to the collision list,*/
void slstore(struct htype *i,struct htype *start)
{
struct htype *old,*p;
old=startp;
/*find end of list */
while(start){
old=start;
start=start->next;
}
/*link in new entry */
old->next=i;
i->next=NULL;
}