c语言给定两个元素有序(从小到大)的链表,要求将两个链表合并成一个有序(从小到大)链表, 要求第一行输入第一个链表的结点数S1,S1<=100。 第二行输入S1个整数,两两之间用空格隔开。 第三行输入第二个链表的结点数S2,S2<=100。 第四行输入S2个整数,两两之间用空格隔开。
时间: 2023-05-27 11:05:28 浏览: 181
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int data;
struct Node *next;
} Node;
Node *createList(int size) {
Node *head = NULL;
Node *tail = NULL;
for (int i = 0; i < size; i++) {
Node *node = (Node*)malloc(sizeof(Node));
scanf("%d", &node->data);
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
return head;
}
Node *mergeList(Node *head1, Node *head2) {
Node *head = NULL;
Node *tail = NULL;
while (head1 != NULL && head2 != NULL) {
Node *node = (Node*)malloc(sizeof(Node));
if (head1->data <= head2->data) {
node->data = head1->data;
head1 = head1->next;
} else {
node->data = head2->data;
head2 = head2->next;
}
node->next = NULL;
if (head == NULL) {
head = node;
tail = node;
} else {
tail->next = node;
tail = node;
}
}
if (head1 != NULL) {
if (head == NULL) {
head = head1;
} else {
tail->next = head1;
}
}
if (head2 != NULL) {
if (head == NULL) {
head = head2;
} else {
tail->next = head2;
}
}
return head;
}
void printList(Node *head) {
while (head != NULL) {
printf("%d ", head->data);
head = head->next;
}
printf("\n");
}
int main() {
int size1, size2;
scanf("%d", &size1);
Node *head1 = createList(size1);
scanf("%d", &size2);
Node *head2 = createList(size2);
Node *head = mergeList(head1, head2);
printList(head);
return 0;
}
阅读全文