C - How do you call the first element in a linked list?

情到浓时终转凉″ 提交于 2019-12-13 07:46:57

问题


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. 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;
}
   }

回答1:


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. The while loop is never entered, since temp is initially defined as NULL, so temp != NULL can't be true. You then set top = temp;, so now top = NULL.



来源:https://stackoverflow.com/questions/14915462/c-how-do-you-call-the-first-element-in-a-linked-list

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!