已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。(学生总数小于100)第一行,a、b两个链表元素的数量N、M,用空格隔开。 接下来N行是a的数据 然后M行是b的数据 每行数据由学号和成绩两部分组成,用c语言编写
时间: 2024-02-06 11:09:57 浏览: 28
以下是一个参考代码,实现了将两个链表合并并按学号升序排列的功能:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct student {
int id;
int score;
struct student* next;
} Student;
Student* insert(Student* head, int id, int score) {
Student* new_node = (Student*) malloc(sizeof(Student));
new_node->id = id;
new_node->score = score;
new_node->next = NULL;
if (head == NULL) {
head = new_node;
} else {
Student* cur = head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = new_node;
}
return head;
}
Student* merge(Student* a, Student* b) {
Student* head = NULL;
while (a != NULL && b != NULL) {
if (a->id < b->id) {
head = insert(head, a->id, a->score);
a = a->next;
} else {
head = insert(head, b->id, b->score);
b = b->next;
}
}
while (a != NULL) {
head = insert(head, a->id, a->score);
a = a->next;
}
while (b != NULL) {
head = insert(head, b->id, b->score);
b = b->next;
}
return head;
}
void print_list(Student* head) {
Student* cur = head;
while (cur != NULL) {
printf("ID: %d, Score: %d\n", cur->id, cur->score);
cur = cur->next;
}
}
int main() {
int n, m;
scanf("%d %d", &n, &m);
Student* head_a = NULL;
Student* head_b = NULL;
int id, score;
for (int i = 0; i < n; i++) {
scanf("%d %d", &id, &score);
head_a = insert(head_a, id, score);
}
for (int i = 0; i < m; i++) {
scanf("%d %d", &id, &score);
head_b = insert(head_b, id, score);
}
Student* merged_list = merge(head_a, head_b);
print_list(merged_list);
return 0;
}
```
输入格式:
```
3 4
1001 90
1002 80
1003 85
1004 95
1005 92
1006 88
1007 91
```
输出结果:
```
ID: 1001, Score: 90
ID: 1002, Score: 80
ID: 1003, Score: 85
ID: 1004, Score: 95
ID: 1005, Score: 92
ID: 1006, Score: 88
ID: 1007, Score: 91
```