2013-10-03 98 views
1

我對無限循環感到生氣,你認爲什麼是合適的解決方案?在C++中對鏈表進行排序

void sorting() { 
    node * temphead = head; 
    node * tempnode = NULL; 

    for (int i=0; i<count; i++) { 
    for (int j=0; j<count-i; j++) { 
     if (temphead->data > temphead->next->data) { 
     tempnode = temphead; 
     temphead = temphead->next; 
     temphead->next = tempnode; 
     } 

     temphead=temphead->next; 
     count++; 
    } 
    } 
} 

我試圖增量次數和使用前,用while-很多條件,後爲沒有結果環路

回答

3

一個簡單的方法,通過一個鏈表下滑是這樣的:

for (node *current = head; current != nullptr; current = current->next) { 
    // This will run through all of the nodes until we reach the end. 
} 

,滑TH Ë倒數第二個項目(確保node->next存在)看起來是這樣的:

for (node *current = head; current->next != nullptr; current = current->next) { 
    // Go through all of the nodes that have a 'next' node. 
} 

如果要統計有多少項目在一個鏈表,你做這樣的事情:

int count = 0; 
for (node *current = head; current != nullptr; current = current->next) { 
    count = count + 1; 
} 

所以就像你有一個以上的選擇類型排序是這樣的:

for (node *index = head; index->next != nullptr; index = index->next) { 
    for (node *selection = index->next; selection != nullptr; selection = selection->next) { 
    if (index->data > selection->data) { 
     swap(index->data, selection->data); 
    } 
    } 
} 

雖然排序鏈表一般是不會去(除非你執行合併)的最佳方式。

+0

我明白了,這就是我真正需要的,但是當我在屏幕上仍然沒有排序:(。謝謝你的建議。 –

+0

嗯..我從內存,我會盡快調試它並重新發布工作版本 – sircodesalot

+0

修正了與其交換節點本身,我只是交換了數據。 – sircodesalot

2

問題是您的循環,直到計數和你在的每一個運行遞增計數循環//刪除行數++避免刪除無限循環

+0

看起來他想循環遍歷列表(按count)並在同一個循環中對元素進行計數:) – Slava

+0

應該有重複計數變量,例如count1(或者更好地重新命名爲size和count),如果您嘗試像什麼@Slava說 –

+0

刪除計數不起作用 –