[英]C - How do you call the first element in a linked list?
I am trying to get a linked list to sort, then be able to display it. 我试图获取一个链表进行排序,然后能够显示它。 The problem with my code is, I can display it before sorting, but after sorting, it won't display, it will crash. 我的代码的问题是,我可以在排序之前显示它,但是在排序之后,它不会显示,它将崩溃。 I think it has to do with the "top" variable, because through debugging, it doesn't contain anything. 我认为它与“ top”变量有关,因为通过调试,它不包含任何内容。 How can I call the first element in the linked list and use that to display them all? 如何调用链接列表中的第一个元素,并使用它显示所有元素? I am just really confused. 我真的很困惑。 Below is only the display and sort functions. 以下仅是显示和排序功能。
//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;
}
}
Your "sort" function is doing nothing except setting the head of your list to "NULL," so you don't actually have a list at all any more. 您的“排序”功能除了将列表的开头设置为“ NULL”之外什么也不做,因此您实际上根本没有列表。 The while
loop is never entered, since temp
is initially defined as NULL
, so temp != NULL
can't be true. 永远不会进入while
循环,因为temp
最初被定义为NULL
,所以temp != NULL
不能为true。 You then set top = temp;
然后设置top = temp;
, so now top = NULL
. ,所以现在top = NULL
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.