2014-02-12 23 views
1

假設我fread() - 多個項目,每個項目都存儲在一個結構中,並用一個指示其順序的整型變量存儲。因此,像這樣:在C:如何構建一個基於變量的順序鏈表?

struct book { 
    int order; 
} 

我也是構建一個鏈表來包含所有的書籍閱讀,使得本書以最小的「訂單」會頭。

鏈表聲明如下:

struct list { 
    struct book p; 
    struct list *next; 
} 

因爲我讀都以隨機順序書,並沒有先前的指針,我應該如何確保我可以用找書最小的順序,並使其成爲我的鏈接列表的頭部?

這是我迄今爲止,它只是增加了他們在隨機順序:

list *lst, *temp; 
struct book buff2; 

lst=malloc(sizeof(struct list)); 

while((nread2=fread(&buff2,sizeof(buff2),1,infp))>0) { 

     temp = malloc(sizeof(*temp)); 
     temp->p=buff2; 
     lst->next=temp; 
     lst=temp; 
} 

謝謝!

+0

如果你是誰問同一個人http://stackoverflow.com/questions/21741909/check-if-an-element-already-exist-in-a-linked-list-in-c/21742055 - 放棄鏈接列表,改用二叉搜索樹。 –

+0

最好解釋一下爲什麼二叉搜索樹是一個比告訴他(或她)「放棄鏈表」更好的選擇。另外,二叉搜索樹比鏈表要複雜一點 - 所以,寶貝步驟可能是最好的。 –

回答

0

爲了讓您的列表從最小到最大,您可以執行以下操作,但您應該記住,這不是此任務的最佳數據結構。

請注意,我既沒有編譯過,也沒有測試過這個代碼 - 它只是一個聲音的起點,你可以用它來展示迭代器和插入的想法。

// Declare lst (head), item (new item), and a list iterator (iter). 
list *lst = NULL, *item = NULL, *iter = NULL; // Initialize all to NULL. 
struct book buff2; 

while ((nread2 = fread(&buff2, sizeof(buff2), 1, infp)) > 0) { // Read item. 
    item = malloc(sizeof(list)); // Allocate node for new item. 
    item->p = buff2; // Assignment to the new node data. 
    item->next = NULL; // Initialize the next to NULL. 

    if (lst == NULL) lst = temp; // Add item to blank list. 
    else { // List has items, find insertion point, then insert. 
     // lst is always the first item (or head). iter moves down list. 
     iter = lst; 

     // Find the insertion point, taking order into consideration. 
     while ((iter->next != NULL) && (iter->p.order < temp->p.order)) 
      iter = iter->next; // Move the iterator down the list. 

     // We now just need to insert our new node into the list. Adjust nexts. 
     item->next = iter->next; // New item takes over the insertion item next. 
     iter->next = item; // Change insertion next to point to the new item. 
    } 
} 
相關問題