繁体   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