2013-02-17 128 views
-1

下面是我使用鏈接列表代碼的插入排序。我已經調試過,沒有其他的,但無法弄清楚如何進行排序。因爲它現在就位於insert()中,所以它進入if語句的無限循環。我需要改變什麼?C-插入排序鏈接列表

//Sort function to call insertion sort function 
void sortEmps() 
{ 
temp = NULL; 
struct EMP* next = top; 

while(top != 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; 
} 
} 

這是我的結構和添加功能。幾乎是排序前使用的唯一東西。我能夠初始化一羣員工,因此他們被存儲。

typedef struct EMP 
{ 
int id; 
char name [MAX]; 
double salary; 
struct EMP* next; 

} EMPLOYEE;               
int addEmployee(char* name, double salary) 
{ 
struct EMP* emp = createEmployee(name, salary); 
emp -> next = top; 
top = emp; 

numEmps++; 
//employees[numEmps++] = emp; 
return TRUE; 
} 
+3

要求人們代碼中的現貨錯誤並不是特別有效。您應該使用調試器(或添加打印語句)來隔離問題(即其行爲與您預期/期望的行爲不同),然後構造一個[最小測試用例](http://sscce.org)。 – 2013-02-17 20:35:43

+0

試圖找到錯誤,但缺少關鍵部分(main()和struct-def),所以我無法找到它。 – 2013-02-17 20:49:23

+0

我下來投票,因爲我看到相同的問題,其中已經問過你的相同的代碼。 – Michael 2013-02-18 06:03:07

回答

0

認爲會發生什麼,如果你想插入到現有的列表和電流 - > ID> EMP-> ID(你從來沒有進入while循環,你的上一張== NULL,所以通過改變指針名單的頭指向別的東西,因此在內存的某個地方失去你的清單未dealocated,你是在玩火

BTW:它有沒有關係,你的插入排序

我不會在這裏寫下你寫這種類型代碼的正確方法,你可以在網上找到足夠的信息。

一些建議,鬆散您的全局指針,並閱讀如何設計一個支持從頭部輕鬆插入和刪除的鏈表(它可能會說一些更多的結構,你應該使用)