C - 如何调用链表中的第一个元素?

时间:2013-02-16 21:45:26

标签: c linked-list insertion-sort

我正在尝试获取一个链表进行排序,然后才能显示它。 我的代码的问题是,我可以在排序之前显示它,但在排序后,它将不会显示,它将崩溃。我认为它与“top”变量有关,因为通过调试,它不包含任何内容。如何调用链表中的第一个元素并使用它来显示所有元素?我真的很困惑。 下面只是显示和排序功能。

//Sort and display all employees
void displayAllEmps()
{
if(numEmps == 0)
{
    printf("No employees are hired.");
    fflush(stdout);
}
else
{
    char output[80];
    struct EMP* emp = top;

    int i;
    for(i = 1; i < numEmps; i++)
    {
        if (emp != NULL)
        {
            displayEmployee(emp, output);

            printf("%s", output);
            fflush(stdout);
        }
        emp = emp -> next;
    }

}
}

//Sort function to call insertion sort function
void sortEmps()
{
temp = NULL;
struct EMP* next = top;

while(temp != NULL)
{
    next = top -> next;
    insert(temp);
    temp = next;
}

top = temp;
}

//Insertion sort function
void insert(struct EMP *emp)
{
prev = NULL;
current = temp;

while (current != NULL && current->id < emp->id)
{
    prev = current;
    current = current->next;
}

if (prev == NULL)
{
    temp = emp;
}
else
{
    emp -> next = prev -> next;
    prev -> next = emp;
}
   }

1 个答案:

答案 0 :(得分:2)

你的“排序”功能除了将列表的头部设置为“NULL”之外什么都不做,所以你实际上根本没有列表了。永远不会输入while循环,因为temp最初定义为NULL,因此temp != NULL不能为真。然后,您设置top = temp;,现在top = NULL

相关问题