从键盘中输入链表节点信息为学号、姓名、成绩。现有两个静态链表分别包含三个节点。用C语言编程实现两个链表的合并然后输出。
时间: 2023-06-27 09:05:17 浏览: 94
以下是一个简单的实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 20
typedef struct Student {
char id[MAX_LEN];
char name[MAX_LEN];
int score;
struct Student* next;
} Student;
Student* create_list(int n) {
Student* head = NULL;
Student* tail = NULL;
for (int i = 0; i < n; i++) {
Student* node = (Student*)malloc(sizeof(Student));
printf("请输入第%d个学生的信息(学号 姓名 成绩):", i+1);
scanf("%s %s %d", node->id, node->name, &node->score);
node->next = NULL;
if (head == NULL) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
return head;
}
void print_list(Student* head) {
printf("学号\t\t姓名\t成绩\n");
while (head != NULL) {
printf("%s\t%s\t%d\n", head->id, head->name, head->score);
head = head->next;
}
}
Student* merge_lists(Student* list1, Student* list2) {
Student* head = NULL;
Student* tail = NULL;
while (list1 != NULL && list2 != NULL) {
Student* node = (Student*)malloc(sizeof(Student));
if (strcmp(list1->id, list2->id) < 0) {
memcpy(node, list1, sizeof(Student));
list1 = list1->next;
} else {
memcpy(node, list2, sizeof(Student));
list2 = list2->next;
}
node->next = NULL;
if (head == NULL) {
head = node;
} else {
tail->next = node;
}
tail = node;
}
if (list1 != NULL) {
tail->next = list1;
}
if (list2 != NULL) {
tail->next = list2;
}
return head;
}
int main() {
printf("请输入第一个链表的节点数:");
int n1;
scanf("%d", &n1);
Student* list1 = create_list(n1);
printf("请输入第二个链表的节点数:");
int n2;
scanf("%d", &n2);
Student* list2 = create_list(n2);
Student* merged_list = merge_lists(list1, list2);
printf("合并后的链表为:\n");
print_list(merged_list);
return 0;
}
```
这个程序中,我们首先定义了一个 `Student` 结构体来表示学生信息,其中包含了学号、姓名、成绩和一个指向下一个节点的指针。然后通过 `create_list` 函数分别创建了两个链表,并通过 `merge_lists` 函数将两个链表合并为一个新链表。最后通过 `print_list` 函数输出合并后的链表。
阅读全文