我比較新的指針C &。我正在嘗試排序,然後打印一個結構鏈表。要麼我錯過了一個邏輯錯誤,要麼我沒有完全理解指針。有人可以向我解釋我在這段代碼中缺少的東西嗎?提前謝謝你!無限循環與指針 - 爲什麼?
// *** Sort Linked List (Merge Sort) ***
struct address_node *newRoot;
// ptr, rearPtr, and tempRoot are also struct Pointers
newRoot = root;
root = root->next;
while (root != NULL)
{
tempRoot = root;
ptr = newRoot;
rearPtr = newRoot;
while (ptr != NULL)
{
printf("here");
if ((root->frequency) == (ptr->frequency))
{ // SPECIAL CASE: To determine read hierarchy for repeated
// Entries
if ((root->read_order) < (ptr->read_order))
{
if (ptr == newRoot)
{
root = root->next;
tempRoot->next = newRoot;
newRoot = tempRoot;
ptr = NULL;
}
else
{
root = root->next;
tempRoot->next = ptr;
rearPtr->next = tempRoot;
ptr = NULL;
}
}
}
else if ((root->frequency) > ptr->frequency)
{ // To ADD BEFORE an ENTRY
if (ptr == newRoot)
{
root = root->next;
tempRoot->next = newRoot;
newRoot = tempRoot;
ptr = NULL;
}
else
{
root = root->next;
tempRoot->next = ptr;
rearPtr->next = tempRoot;
ptr = NULL;
}
}
else if (ptr->next == NULL)
{ // if END OF LIST
root = root->next;
ptr->next = tempRoot;
ptr = NULL;
}
else
{ // SPOT NOT FOUND YET< MOVE FORWARD THROUGH LIST
rearPtr = ptr;
ptr = ptr->next;
}
}
}
// *** PRINT ***
ptr = newRoot;
if (numOut == 0)
{
while (ptr != NULL)
{
printf("0x%zx :%d\n", ptr->address, ptr->frequency);
ptr = ptr->next;
}
}
else
{
while (ptr != NULL && numOut > 0)
{
printf("0x%zx :%d\n", ptr->address, ptr->frequency);
numOut--;
ptr = ptr->next;
}
}
目前循環永不退出? – canhazbits
要做的第一件事是編寫兩個單獨的函數(至少),一個合併排序鏈接列表,另一個打印鏈接列表。您將使用打印功能在各個階段打印鏈接列表,同時調試您的排序代碼。這些函數應該列出一個列表(對於打印函數,我推薦一個'標籤' - 一個字符串,它將在列表內容之前打印出來 - 也可能是文件流:void print_list(const char * tag,struct address_node const * list)'或'void print_list(FILE * fp,const char * tag,struct address_node const * list)')。 –
列表的經典合併排序算法將給定列表拆分爲兩個單獨列表,合併排序每個單獨列表(遞歸),然後將生成的已排序單獨列表合併到輸出列表中。你的代碼似乎沒有遵循這種模式。請在SO搜索框中查找'[c]合併排序列表'。它可能會導致你[使用mergesort排序鏈表](http://stackoverflow.com/questions/19016840/using-mergesort-to-sort-linked-lists/),也可能導致其他問題。 –