读书人

c语言链表查找有关问题

发布时间: 2013-03-27 11:22:42 作者: rapoo

c语言链表查找问题



楼主 发表于: 2013-03-22 23:23:21

printf("请输入姓名: ");
scanf("%s",str);
if(strcmp(p->name,str)==0)
{
printf("您所查找的同学信息如下:\n");
search_print(p);
}
else
{
while(p->next!=NULL&&strcmp(p->next->name,str)!=0)
{
p=p->next;
}
if(p->next==NULL)
{
printf("It haven't this name\n");
}
else
{
printf("您所查找的同学信息如下:\n");
search_print(p->next);
}
}
求大神指点,这是成绩管理程序的一部分,就是按姓名查找成绩,输入查找姓名,如果一个班有相同姓名的人,他怎么只打印第一个相同姓名的学生成绩,另一个却没有!求指点 c search
[解决办法]
逻辑有点乱,还有就是不知道那个search_print(p->next)是不是用来输出成绩信息的。猜想你的意思是:
p是存储学生信息的链表,得到用户输入后先比较链表中第一个element,如果是就用search_print打印成绩,否则开始查询。那么可能的原因就是,每次查找到第一个名字相符的element,查询就结束开始打印输出了。

      
while(p->next!=NULL&&strcmp(p->next->name,str)!=0)
{
p=p->next;
}


解决的方法也简单,遍历链表即可。为了判断找到符合条件元素的数量,还可以引入一个变量进行计数

// add this count at the beginning of your code
int iFoundCount =0;

...
//using below code to replace original part in else branch


while(NULL!=p->next)
{
//check if identifical name found
if(!strcmp(p->next->name,str))
{
iFoundCount++;
printf("您所查找的同学信息如下:\n");
search_print(p->next);
}

p=p->next;
}

//Nothing be found
if(!iFoundCount)
{
printf("It haven't this name\n");
}
else
{
printf("Search completed");
}




实际上,没有必要单独比较第一个元素,完全可以统一处理

void Search(Student* p )
{
int iFoundCount =0;

printf("请输入姓名: ");
scanf("%s",str);

if(NULL==p)
{
printf("ERROR: NULL Linklist! ");
}
else
{
while(NULL!=p)
{
//check if identifical name found
if(!strcmp(p->name,str))
{
iFoundCount++;
printf("您所查找的同学信息如下:\n");
//assume your function "search_print()" is used to output student score
search_print(p);
}

p=p->next;
}

//Nothing be found
if(!iFoundCount)
{
printf("It haven't this name\n");
}
else
{
printf("Search completed");
}
}


}

读书人网 >C语言

热点推荐