I'm望着例如6.7 http://publications.gbdirect.co.uk/c_book/chapter6/structures.html排序單鏈表 - 我不明白
(粘貼在這裏爲方便起見)
struct list_ele *
sortfun(struct list_ele *list)
{
int exchange;
struct list_ele *nextp, *thisp, dummy;
/*
* Algorithm is this:
* Repeatedly scan list.
* If two list items are out of order,
* link them in the other way round.
* Stop if a full pass is made and no
* exchanges are required.
* The whole business is confused by
* working one element behind the
* first one of interest.
* This is because of the simple mechanics of
* linking and unlinking elements.
*/
dummy.pointer = list;
do{
exchange = 0;
thisp = &dummy;
while((nextp = thisp->pointer)
&& nextp->pointer){
if(nextp->data < nextp->pointer->data){
/* exchange */
exchange = 1;
thisp->pointer = nextp->pointer;
nextp->pointer =
thisp->pointer->pointer;
thisp->pointer->pointer = nextp;
}
thisp = thisp->pointer;
}
}while(exchange);
return(dummy.pointer);
}
我得到的基本想法,但我真的不能解釋那裏發生了什麼。有人可以更深入地解釋,但以簡單的方式解釋這種功能正在發生什麼?
一些普遍問題:
- 爲什麼
dummy.pointer = list;
需要?dummy
然後在函數結束時返回,列表如何仍然排序? - 評論
The whole business is confused by working one element behind the first one of interest.
是什麼意思?
謝謝你的解釋,它使得它更清楚虛擬做什麼,特別是與thisp結合使用。我覺得很難理解:爲什麼需要do/while結構?在我天真的想法中,我只是遍歷列表並進行交換... – Max
@Max考慮列表c => b => a。經過內循環一次,你得到b => a => c(用c交換b,用c交換a)。您需要繼續瀏覽清單,直到您不進行任何交流。只有在那個時候你才知道整個清單是有序的。這就是外部循環所保證的。 – tvanfosson