I have a problem with sorting my linked list. I want to sort it twice, like this:
我在排序链表时遇到问题。我想对它进行两次排序,如下所示:
Input
char cl; int time; int lng;
A 2 2
B 2 1
C 0 2
D 0 1
I want the output to look like this :
我希望输出看起来像这样:
C 0 1
D 0 2
B 2 1
A 2 2
As you can see the output that I want is sorted by the second and the third column. I was only able to sort by the second column using this code.
如您所见,我想要的输出按第二列和第三列排序。我只能使用此代码按第二列排序。
void sort (const node *n)
{
node *list,*pass;
list = n;
for (; list->next != NULL; list = list->next)
{ for (pass=list->next; pass!=NULL; pass=pass->next)
if (list->time < pass->time)
{ swap(list, pass);
}
}
}
1 个解决方案
#1
3
John C gives you a nice hint (check from least-significant key to most-significant key):
John C为您提供了一个很好的提示(从最重要的密钥到最重要的密钥检查):
int comp(const void *pa, const void *pb)
{
const node *a = (const node *)pa;
const node *b = (const node *)pb;
return (a->lng < b->lng) ? 1 :
(a->time < b->time) ? 1 :
(a->cl < b->cl) ? 1 : 0;
}
void sort(const node *n, int (*comp)(const void *, const void *))
{
node *list, *pass;
list = n;
for (; list->next != NULL; list = list->next) {
for (pass=list->next; pass!=NULL; pass=pass->next) {
if (comp(list, pass)) {
swap(list, pass);
}
}
}
}
Call it using:
用它来调用:
sort(node, comp);
#1
3
John C gives you a nice hint (check from least-significant key to most-significant key):
John C为您提供了一个很好的提示(从最重要的密钥到最重要的密钥检查):
int comp(const void *pa, const void *pb)
{
const node *a = (const node *)pa;
const node *b = (const node *)pb;
return (a->lng < b->lng) ? 1 :
(a->time < b->time) ? 1 :
(a->cl < b->cl) ? 1 : 0;
}
void sort(const node *n, int (*comp)(const void *, const void *))
{
node *list, *pass;
list = n;
for (; list->next != NULL; list = list->next) {
for (pass=list->next; pass!=NULL; pass=pass->next) {
if (comp(list, pass)) {
swap(list, pass);
}
}
}
}
Call it using:
用它来调用:
sort(node, comp);