已有a、b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按学号升序排列。(学生总数小于100)c语言
时间: 2024-01-24 09:16:48 浏览: 63
以下是一个示例代码,实现了链表的合并和排序功能:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
struct Node {
int id;
int score;
struct Node* next;
};
// 创建新结点
struct Node* createNode(int id, int score) {
struct Node* node = (struct Node*)malloc(sizeof(struct Node));
node->id = id;
node->score = score;
node->next = NULL;
return node;
}
// 插入结点到链表末尾
void insertNode(struct Node** head, struct Node* node) {
if (*head == NULL) {
*head = node;
} else {
struct Node* cur = *head;
while (cur->next != NULL) {
cur = cur->next;
}
cur->next = node;
}
}
// 合并两个链表
struct Node* mergeLists(struct Node* list1, struct Node* list2) {
struct Node* head = NULL;
while (list1 != NULL && list2 != NULL) {
if (list1->id < list2->id) {
insertNode(&head, createNode(list1->id, list1->score));
list1 = list1->next;
} else {
insertNode(&head, createNode(list2->id, list2->score));
list2 = list2->next;
}
}
while (list1 != NULL) {
insertNode(&head, createNode(list1->id, list1->score));
list1 = list1->next;
}
while (list2 != NULL) {
insertNode(&head, createNode(list2->id, list2->score));
list2 = list2->next;
}
return head;
}
// 打印链表
void printList(struct Node* head) {
struct Node* cur = head;
while (cur != NULL) {
printf("id: %d, score: %d\n", cur->id, cur->score);
cur = cur->next;
}
}
int main() {
// 创建链表1
struct Node* list1 = createNode(1, 90);
insertNode(&list1, createNode(3, 70));
insertNode(&list1, createNode(5, 85));
insertNode(&list1, createNode(7, 95));
printf("List1:\n");
printList(list1);
// 创建链表2
struct Node* list2 = createNode(2, 80);
insertNode(&list2, createNode(4, 65));
insertNode(&list2, createNode(6, 75));
insertNode(&list2, createNode(8, 88));
printf("List2:\n");
printList(list2);
// 合并链表并按学号排序
struct Node* mergedList = mergeLists(list1, list2);
printf("Merged list:\n");
printList(mergedList);
return 0;
}
```
以上代码中,我们首先定义了一个链表结构体 `Node`,包括学号和成绩两个属性以及指向下一个结点的指针。然后,我们编写了创建结点、插入结点、合并链表和打印链表等函数。在主函数中,我们创建了两个链表 `list1` 和 `list2`,并按顺序插入结点。然后,我们调用 `mergeLists` 函数将两个链表合并,并按学号升序排序。最后,我们打印出合并后的链表 `mergedList`。
阅读全文