gpt4 book ai didi

c - 按多个参数对链表进行排序

转载 作者:太空宇宙 更新时间:2023-11-04 04:33:16 25 4
gpt4 key购买 nike

我正在尝试在单链表上使用插入排序,其中每个节点都有多个参数,例如:

typedef struct _node {
char param1[10];
char param2[10];
char param3[10];
struct _node *next;
} node;

该算法将按 param1 对列表进行排序,如果项目相同,则由 param2 决定顺序,类似地由 param3 决定顺序。我无法在线找到解决此问题的方法。对于单个参数,我有以下排序算法的实现:

void insertionSort(node **head) {

//Initialize sorted list
node *sorted = NULL;
node *current = *head;

//Insert every node into sorted list
while (current != NULL) {
// Store next for next iteration
node *next = current->next;

sortedInsert(&sorted, current);

// Update current
current = next;
}

//Replace old empty list with sorted list
*head = sorted;
}

void sortedInsert(node **head, node *new) {
node *current = *head;
// Special case for the head
if (current == NULL || strcmp(current->param1, new->param1) >= 0) {
new->next = current;
*head = new;
}

else {
while (current->next!=NULL && strcmp(current->next->param1, new->param1) < 0){
current = current->next;
}

new->next = current->next;
current->next = new;
}
}

我的猜测是我必须创建一个比较函数而不是以下位,可能是一个返回 0 或 1 的整数函数,对应于这两种情况:

current->param1 >= new->param1
current->next->param1 < new->param1

但是,我无法想出这样的功能。谁能帮我解决这个问题?

最佳答案

一个排序例程,通过比较来决定之前或之后的内容。如果比较是在一个函数中完成的,那么元素的顺序由返回决定(例如小于零(一般为-1)、零、大于零(一般为的返回>1))。

如果您按主要参数排序并遇到等价项,则按次要字符串进行比较并使用这些结果进行放置。在大多数情况下,比较函数将采用指向每个被比较节点的空指针。通过这种方式,您将可以访问排序函数中的主要和次要字符串。只需在排序函数中包含二次比较,以防第一次比较的结果为零,并根据二次比较的结果返回 (-1, 0, 1)。

关于c - 按多个参数对链表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33728844/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com