2013-02-16 25 views
-1

我想獲得一個鏈表來排序,然後能夠顯示它。 我的代碼的問題是,我可以在排序之前顯示它,但排序後,它不會顯示,它會崩潰。我認爲它與「top」變量有關,因爲通過調試,它不包含任何內容。我如何調用鏈表中的第一個元素並使用它來顯示它們全部?我真的很困惑。 下面只是顯示和排序功能。C - 你如何調用鏈表中的第一個元素?

//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; 
} 
    } 
+0

您能否給我們提供您遇到的實際錯誤? – 2013-02-16 21:47:52

+1

我認爲你需要emp = emp - > next;在if(emp!= NULL){}之內,否則當emp爲NULL時,您將解引用空指針。 – 2013-02-16 21:50:20

+0

它沒有給出實際的錯誤。它只是在displayAll函數中崩潰,在任何地方使用「emp」。 「top」在排序之後不會給任何東西,所以我認爲「top」需要改變,但是idk要做什麼。 – 2013-02-16 21:52:06

回答

2

您的「排序」函數除了將列表頭設置爲「NULL」之外什麼都不做,因此您實際上沒有任何列表。從不輸入while循環,因爲temp最初定義爲NULL,所以temp != NULL不能爲真。然後您設置top = temp;,所以現在top = NULL

相關問題