用C语言编译已有a,b两个链表,每个链表中的结点包括学号、成绩。要求把两个链表合并,按照学号升序排列
时间: 2023-07-11 07:29:57 浏览: 137
以下是用C语言编写的合并两个链表,并按照学号升序排列的代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int num;
int score;
struct Node* next;
};
struct Node* merge(struct Node* head1, struct Node* head2) {
struct Node* p1 = head1;
struct Node* p2 = head2;
struct Node* newHead = NULL;
struct Node* tail = NULL;
while (p1 != NULL && p2 != NULL) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
if (p1->num < p2->num) {
newNode->num = p1->num;
newNode->score = p1->score;
p1 = p1->next;
} else {
newNode->num = p2->num;
newNode->score = p2->score;
p2 = p2->next;
}
newNode->next = NULL;
if (newHead == NULL) {
newHead = newNode;
tail = newNode;
} else {
tail->next = newNode;
tail = newNode;
}
}
while (p1 != NULL) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->num = p1->num;
newNode->score = p1->score;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
p1 = p1->next;
}
while (p2 != NULL) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->num = p2->num;
newNode->score = p2->score;
newNode->next = NULL;
tail->next = newNode;
tail = newNode;
p2 = p2->next;
}
return newHead;
}
int main() {
// 创建链表1
struct Node* head1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node1_1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node1_2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node1_3 = (struct Node*)malloc(sizeof(struct Node));
head1->num = 2;
head1->score = 90;
node1_1->num = 4;
node1_1->score = 80;
node1_2->num = 6;
node1_2->score = 70;
node1_3->num = 8;
node1_3->score = 85;
head1->next = node1_1;
node1_1->next = node1_2;
node1_2->next = node1_3;
node1_3->next = NULL;
// 创建链表2
struct Node* head2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2_1 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2_2 = (struct Node*)malloc(sizeof(struct Node));
struct Node* node2_3 = (struct Node*)malloc(sizeof(struct Node));
head2->num = 1;
head2->score = 95;
node2_1->num = 3;
node2_1->score = 88;
node2_2->num = 5;
node2_2->score = 75;
node2_3->num = 7;
node2_3->score = 92;
head2->next = node2_1;
node2_1->next = node2_2;
node2_2->next = node2_3;
node2_3->next = NULL;
// 合并链表并排序
struct Node* newHead = merge(head1, head2);
struct Node* p = newHead;
while (p != NULL) {
printf("num=%d, score=%d\n", p->num, p->score);
p = p->next;
}
return 0;
}
```
注:上述代码只是一种实现方式,还有其他方法可以达到同样的效果。
阅读全文