单链接列表无法正确添加

时间:2014-04-24 20:26:07

标签: c sorting linked-list structure nodes

我正在尝试将学生记录(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 failed\n");
        }

    return listStart;

1 个答案:

答案 0 :(得分:0)

比较相反:

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} })。由于您正在测试相反的条件,-1会追溯insert