2013-10-15 38 views
0

我想通過節點struct(age)內的int值重新排序我的DLL。它工作時,我直接訪問int,但我試圖交換整個節點,這樣我就不必在列表重新排序時交換結構中的每個變量。雙鏈表列表節點交換問題

void DLL::ReOrg(node* head, int DLL_Size) 
{ 

node* temp = head; 
int holder; 


for(int j = 0; j < DLL_Size; j++) 
{ 

     while(temp != NULL) 
     { 

        if (temp->next != NULL && (temp->age < temp->next->age)) 
        { 
         holder = temp->age; 

         temp->age = temp->next->age; 
         temp->next->age = holder; 
        } 
        else 
          temp = temp->next;//increment node 
      } 
      temp = head; 

} 


} 

這個工作,但是當我試着這樣做:

node* holder; 

... 

holder = temp; 
temp = temp->next; 
temp->next = holder; 

我的程序編譯和運行一個空白屏幕。任何指導將不勝感激。我猜測只需要交換所有變量(並不是很多),但我想讓代碼更清晰。謝謝。

回答

0

這是因爲你實際上沒有重新鏈接節點,所以你會得到一個無限循環。您需要更改前一個節點的next鏈接以及下一個下一個節點上的prev鏈接。


如果你的名單雙向鏈接,和你有一指針和下一指針,那麼你可以做這樣的事情:

node* next = temp->next; 

// Fix the links of the previous node, and the next-next node 
if (temp->prev) 
    temp->prev->next = next; 

if (next->next) 
    next->next->prev = temp; 

// Relink the two nodes that should be swapped 
temp->next = next->next; 
next->next = temp; 

next->prev = temp->prev; 
temp->prev = next; 
+0

我猜我最初的環節失去了指針。我試着像你說的那樣加上prev-> next&next-> next-> prev,但它仍然是空白的。我討厭鏈接列表 – GeorgeCostanza

+0

@GeorgeCostanza添加了一些示例重新鏈接代碼 –

+0

好吧我幾乎在那裏,但由於某種原因節點在ReOrg期間迷路了。這裏有一張圖片來展示正在發生的事情。 http://i.imgur.com/U3BGstr.png感謝您的時間。我有頭和尾指針指向第一個和最後一個節點。 head-> prev和tail-next是NULL – GeorgeCostanza