PTA习题问题,离大谱了

浙大版《数据结构(第2版)》题目集
习题5.10 线性探测法的查找函数 (20 分)
把两个if条件写开就答案正确

Position Find( HashTable H, ElementType Key )
{
    Position ind;
    int count = 0;
    //循环表长长度
    while(count < H->TableSize){
        //获取Key第一次在的位置
        ind = Hash(Key +count,H->TableSize);
        if(H->Cells[ind].Info == Legitimate){ //就是这里
            if(H->Cells[ind].Data == Key){//还有这里
                return ind;
            }
        }else{
            return ind;
        }
        count++;
    }
    return ERROR;
}

把if的两个条件写在一起,结果就是部分正确

Position Find( HashTable H, ElementType Key )
{
    Position ind;
    int count = 0;
    //循环表长长度
    while(count < H->TableSize){
        //获取Key第一次在的位置
        ind = Hash(Key +count,H->TableSize);
        if(H->Cells[ind].Info == Legitimate && H->Cells[ind].Data == Key){//就是这里
            return ind;
        }else{
            return ind;
        }
        count++;
    }
    return ERROR;
}

因为两种写法并不是等价的。

        if(H->Cells[ind].Info == Legitimate){ //就是这里
            if(H->Cells[ind].Data == Key){//还有这里
                return ind;
            }
        }

这里实际包含了另一个条件,就是内层的if如果没满足,还有else,而这个else是直接返回ERROR
而下面的写法,实际是把条件限定更加严格。

        if(H->Cells[ind].Info == Legitimate && H->Cells[ind].Data == Key){//就是这里
            return ind;
        }

就是必须满足两个条件才返回ind,不满足则进入else,忽略了进入ERROR的条件。
所以程序上面才是正确的。
如有帮助,希望采纳一下

区别在于执不执行else,分开写,满足第一个条件,不满足第二个条件,不会执行else;写在一起,只要一个不满足,就会执行else。