我试图让一个链表进行排序,然后能够显示它。我的代码的问题是,我可以在排序之前显示它,但是排序之后它不会显示,它会崩溃。我认为它与“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;
}
}