簡體   English   中英

如何以正確的方式對鏈接列表進行排序 C

[英]How to sort link list in correct way C

我嘗試按字段年份對鏈表進行排序,但我的代碼不正確。 我有這樣的列表和功能來對鏈表進行排序:

struct sputnik {
char nazvanie[30];
char nazvanie_main[30];
int year;
float d;
int period;
struct sputnik *next;
};

int f_sort (struct sputnik **head,int*count) {
struct sputnik *prev,*current,*buffer, *buf;
int i;
current=*head;

for (i=0;i<*count;i++) {
while (current!=NULL){
prev=current;
buf=current->next;
if (prev->year>buf->year){
buffer=buf->next;
buf->next=prev->next;
prev->next=buffer;
current=prev->next;

}
else{
current=buf->next;
}
}
}
return 0;
}

我的代碼中的計數是我列表中元素的數量。

您需要根據需要更新列表的頭部,並在 for(i = 0 ...) 循環后將 current 重置回列表的頭部。 如果您使用指向當前的指針而不是“prev”的指針,這會更容易。 例如:

struct sputnik **ppcurrent;
    /* ... */
    for(i=0 ...
        ppcurrent = head;
        while(NULL != *ppcurrent && NULL != (*ppcurrent)->next){
            /* ... if swap */
                *ppcurrent = ... ;  /* update head or a next pointer */
            /* ... */
            ppcurrent = &((*ppcurrent)->next); /* advance ppcurrent */

有更好的方法來對列表進行排序,但看看您是否可以先讓當前版本正常工作。


對於閱讀本文的其他人,更好的方法:

鏈表的自下而上歸並排序:

https://en.wikipedia.org/wiki/Merge_sort#Bottom-up_implementation_using_lists

示例 C 代碼:

對鏈表進行合並排序

在大多數情況下,由於分散節點的順序訪問涉及內存的隨機訪問,這對緩存不友好,因此將列表復制到數組,對數組進行排序,然后從數組創建排序列表通常會更快。 這就是 Java 在 collections.sort() 中為原生鏈表所做的。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM