C语言链表排序 交换数据

img


结构体里面是一个char[20] 和一个 int; 想用交换数据进行排序,但是一选排序就没反应了,求指出错误,感谢!

该回答内容部分引用GPT,GPT_Pro更好的解决问题
C语言链表排序交换数据:
要实现链表中char[20]和nt类型数据的排序,首先我们需要对结构体进行定义:

{
  char[20] c;
  int n;
}

然后,我们可以使用冒泡排序方法来实现交换数据的排序,具体的代码如下:

void sort(struct data *head) { struct data *p; struct data *q; for(p=head; p->next!=NULL; p=p->next) { for(q=head; q->next!=NULL; q=q->next) { if (q->n > q->next->n) { char temp_c[20]; int temp_n; strcpy(temp_c, q->c); temp_n = q->n; strcpy(q->c, q->next->c); q->n = q->next->n; strcpy(q->next->c, temp_c); q->next->n = temp_n; } } } }
最后,只要将sort函数传入链表头节点就可以实现将链表中char[20]和nt类型数据进行排序了。
如果回答有帮助,望采纳。

该回答引用GPTᴼᴾᴱᴺᴬᴵ
你可以尝试使用冒泡排序对链表进行排序,实现过程中可以使用交换结点数据的方式。以下是示例代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#define MAX_NAME_LEN 20

// 链表节点结构体
struct node {
    char name[MAX_NAME_LEN];
    int score;
    struct node *next;
};

// 创建节点
struct node* create_node(char *name, int score) {
    struct node *p = (struct node*)malloc(sizeof(struct node));
    strncpy(p->name, name, MAX_NAME_LEN);
    p->score = score;
    p->next = NULL;
    return p;
}

// 在链表末尾插入节点
void insert_node(struct node **head, struct node *p) {
    if (*head == NULL) {
        *head = p;
        return;
    }
    struct node *q = *head;
    while (q->next) {
        q = q->next;
    }
    q->next = p;
}

// 打印链表
void print_list(struct node *head) {
    printf("Name\tScore\n");
    while (head) {
        printf("%s\t%d\n", head->name, head->score);
        head = head->next;
    }
}

// 交换节点数据
void swap_node_data(struct node *p, struct node *q) {
    struct node tmp;
    memcpy(&tmp, p, sizeof(struct node));
    memcpy(p, q, sizeof(struct node));
    memcpy(q, &tmp, sizeof(struct node));
}

// 对链表进行冒泡排序
void sort_list(struct node *head) {
    if (head == NULL || head->next == NULL) {
        return;
    }
    struct node *p, *q, *end = NULL;
    while (end != head->next) {
        p = head;
        q = p->next;
        while (q != end) {
            if (q->score < p->score) {
                swap_node_data(p, q);
            }
            p = p->next;
            q = q->next;
        }
        end = p;
    }
}

int main() {
    // 创建链表
    struct node *head = NULL;
    insert_node(&head, create_node("Tom", 80));
    insert_node(&head, create_node("Jack", 60));
    insert_node(&head, create_node("Mary", 70));
    insert_node(&head, create_node("Lucy", 90));
    insert_node(&head, create_node("David", 75));

    // 打印排序前的链表
    printf("Before sorting:\n");
    print_list(head);

    // 对链表进行排序
    sort_list(head);

    // 打印排序后的链表
    printf("After sorting:\n");
    print_list(head);

    return 0;
}


在 swap_node_data 函数中,我们使用了 memcpy 函数来交换结点数据,这是因为结构体中含有字符数组,不能直接使用赋值符号 = 进行交换。在 sort_list 函数中,我们使用了冒泡排序对链表进行排序,通过调用 swap_node_data 函数来实现结点数据的交换。

不知道你这个问题是否已经解决, 如果还没有解决的话:

如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^