岁晚来相依


私信TA

用户名:uq_34667488517

访问量:199

签 名:

等  级
排  名 22559
经  验 609
参赛次数 0
文章发表 5
年  龄 0
在职情况 学生
学  校
专  业

  自我简介:

TA的其他文章

解题思路:

注意事项:

参考代码:

#include <stdio.h>

#include <stdlib.h>


// 定义链表结构体

typedef struct node {

    int id;         // 学号

    int score;      // 成绩

    struct node *next;  // 指向下一个节点的指针

} Node;


// 插入节点到链表中

void insert(Node **head, int id, int score) {

    Node *new_node = (Node *)malloc(sizeof(Node));

    new_node->id = id;

    new_node->score = score;

    new_node->next = NULL;


    if (*head == NULL) {

        *head = new_node;

    } else {

        Node *cur = *head;

        Node *prev = NULL;

        while (cur != NULL && cur->id < id) {

            prev = cur;

            cur = cur->next;

        }

        if (prev == NULL) {

            new_node->next = *head;

            *head = new_node;

        } else {

            prev->next = new_node;

            new_node->next = cur;

        }

    }

}


// 合并两个链表

Node *merge(Node *a, Node *b) {

    Node *head = NULL;

    Node *cur = NULL;


    while (a != NULL && b != NULL) {

        if (a->id < b->id) {

            if (head == NULL) {

                head = a;

                cur = a;

            } else {

                cur->next = a;

                cur = cur->next;

            }

            a = a->next;

        } else {

            if (head == NULL) {

                head = b;

                cur = b;

            } else {

                cur->next = b;

                cur = cur->next;

            }

            b = b->next;

        }

    }


    if (a != NULL) {

        if (head == NULL) {

            head = a;

        } else {

            cur->next = a;

        }

    }


    if (b != NULL) {

        if (head == NULL) {

            head = b;

        } else {

            cur->next = b;

        }

    }


    return head;

}


// 输出链表

void print(Node *head) {

    while (head != NULL) {

        printf("%d %d\n", head->id, head->score);

        head = head->next;

    }

}


int main() {

    int n, m;

    scanf("%d %d", &n, &m);


    Node *a = NULL;

    Node *b = NULL;


    // 读入a链表的数据

    for (int i = 0; i < n; i++) {

        int id, score;

        scanf("%d %d", &id, &score);

        insert(&a, id, score);

    }


    // 读入b链表的数据

    for (int i = 0; i < m; i++) {

        int id, score;

        scanf("%d %d", &id, &score);

        insert(&b, id, score);

    }


    // 合并两个链表

    Node *c = merge(a, b);


    // 输出链表

    print(c);


    return 0;

}


 

0.0分

1 人评分

看不懂代码?想转换其他语言的代码? 或者想问其他问题? 试试问问AI编程助手,随时响应你的问题:

编程语言转换万能编程问答  

代码解释器

代码纠错

SQL生成与解释

  评论区