我正试图将学生记录(SREC)排序到一个单链表中。这里的记录比较是根据学生的姓氏。下面的代码比较正确,但当它将新记录放在列表的开头时,它会覆盖第二条记录。也就是说,第二个记录稍后打印为完全相同的记录。
帮助?提前感谢!
/*Insert and sort new SREC into each list*/
if(insert != NULL)
{
insert -> next = NULL;
prev = NULL;
current = listStart;
while(current != NULL && strcmp(insert->lname, current->lname) > 0)
{
prev = current;
current = current -> next;
}
if(prev == NULL) /*This is to place the new record at the start of the list*/
{
insert -> next = listStart;
listStart = insert;
}
else
{
prev -> next = insert;
insert -> next = current;
}
}
else
{
printf("Insertion failedn");
}
return listStart;
比较相反:
strcmp(insert->lname, current->lname) > 0
应为:
strcmp(insert->lname, current->lname) < 0
或者:
strcmp(current->lname, insert->lname) > 0
例如,如果current->lname
是"b"
,而insert->lname
是"a"
,则strcmp
将执行'a' - 'b'
(结果:-1
)。由于您正在测试相反的条件,insert
位于current
之后。