4)程序功能:输入若干个学生成绩(输入-1为结束标志),建立两个已按升序排序的单向链表,头指针分别为list1、list2,把两个链表拼成一个升序排序的新链表,并输出新链表信息。要求自定义函数,实现将两个链表拼成一个链表,并返回拼组后的新链表。
时间: 2023-05-11 07:04:58 浏览: 121
可以使用以下代码实现:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *mergeLists(Node *list1, Node *list2) {
Node *head = NULL;
Node **tail = &head;
while (list1 && list2) {
if (list1->data < list2->data) {
*tail = list1;
list1 = list1->next;
} else {
*tail = list2;
list2 = list2->next;
}
tail = &((*tail)->next);
}
*tail = (list1 ? list1 : list2);
return head;
}
int main() {
Node *list1 = NULL;
Node *list2 = NULL;
int score;
printf("请输入学生成绩(输入-1为结束标志):\n");
while (1) {
scanf("%d", &score);
if (score == -1) {
break;
}
Node *node = (Node *)malloc(sizeof(Node));
node->data = score;
node->next = NULL;
if (!list1 || score < list1->data) {
node->next = list1;
list1 = node;
} else {
Node *prev = list1;
Node *cur = list1->next;
while (cur && score >= cur->data) {
prev = cur;
cur = cur->next;
}
node->next = cur;
prev->next = node;
}
}
printf("第一个链表为:\n");
Node *cur = list1;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
printf("请输入学生成绩(输入-1为结束标志):\n");
while (1) {
scanf("%d", &score);
if (score == -1) {
break;
}
Node *node = (Node *)malloc(sizeof(Node));
node->data = score;
node->next = NULL;
if (!list2 || score < list2->data) {
node->next = list2;
list2 = node;
} else {
Node *prev = list2;
Node *cur = list2->next;
while (cur && score >= cur->data) {
prev = cur;
cur = cur->next;
}
node->next = cur;
prev->next = node;
}
}
printf("第二个链表为:\n");
cur = list2;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
Node *mergedList = mergeLists(list1, list2);
printf("合并后的链表为:\n");
cur = mergedList;
while (cur) {
printf("%d ", cur->data);
cur = cur->next;
}
printf("\n");
return 0;
}
阅读全文