[英]C - How do you call the first element in a linked list?
我試圖獲取一個鏈表進行排序,然后能夠顯示它。 我的代碼的問題是,我可以在排序之前顯示它,但是在排序之后,它不會顯示,它將崩潰。 我認為它與“ 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;
}
}
您的“排序”功能除了將列表的開頭設置為“ NULL”之外什么也不做,因此您實際上根本沒有列表。 永遠不會進入while
循環,因為temp
最初被定義為NULL
,所以temp != NULL
不能為true。 然后設置top = temp;
,所以現在top = NULL
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.