我需要根据作为第二个参数传递的任何函数计算出的优先顺序,以升序或降序对列表进行排序。
该算法几乎找到最小值,将其与第一个位置或最后一个位置的值交换,具体取决于作为 sort list( ) 函数调用的第二个参数传递的函数的计算。
这是我的代码,我只是不知道如何实现传递它以升序或降序传递的函数。我的只有一种方式:
#include <stdio.h>
#include <stdlib.h>
typedef struct iorb {
int base_pri;
struct iorb *link;
char filler[100];
} IORB;
int push(struct iorb **h, int x)
{
struct iorb *temp = (struct iorb*)malloc(sizeof(struct iorb));
temp->base_pri = x;
temp->link = *h;
*h = temp;
return 0;
}
void print(struct iorb *head)
{
struct iorb *temp = head;
while(temp != NULL)
{
printf("%d ",temp->base_pri);
temp = temp->link;
}
printf("\n");
}
void sort(struct iorb **h)
{
int a;
struct iorb *temp1;
struct iorb *temp2;
for(temp1=*h;temp1!=NULL;temp1=temp1->link)
{
for(temp2=temp1->link;temp2!=NULL;temp2=temp2->link)
{
if(temp2->base_pri < temp1->base_pri)
{
a = temp1->base_pri;
temp1->base_pri = temp2->base_pri;
temp2->base_pri = a;
}
}
}
}
int main()
{
struct iorb * head = NULL;
push(&head,5);
push(&head,4);
push(&head,6);
push(&head,2);
push(&head,9);
printf("List is : ");
print(head);
sort(&head);
printf("after sorting list is : ");
print(head);
return 0;
}
最佳答案
您需要提供比较器功能。您可以将其作为函数指针传递给排序函数,并使用它们代替内置操作。
像这样:
int less(int lh, int rh)
{
return lh < rh;
}
int greater(int lh, int rh)
{
return !less(lh, rh);
}
void sort(struct iorb **h, bool (*comp)(int, int))
{
int a;
struct iorb *temp1;
struct iorb *temp2;
for(temp1=*h;temp1!=NULL;temp1=temp1->link)
{
for(temp2=temp1->link;temp2!=NULL;temp2=temp2->link)
{
if(comp(temp2->base_pri, temp1->base_pri)) // Using a comparator.
{
a = temp1->base_pri;
temp1->base_pri = temp2->base_pri;
temp2->base_pri = a;
}
}
}
}
然后
sort(&head, less);
或
sort(&head, greater);
关于c - 按升序和降序对列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50252557/