用C语言将两个递增的有序链表合并为一个递增的有序链表
时间: 2023-09-12 17:02:36 浏览: 244
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点
typedef struct node {
int data;
struct node *next;
} Node;
// 创建链表
Node* create_list(int n) {
Node *head = NULL, *p = NULL, *q = NULL;
int i, num;
for (i = 0; i < n; i++) {
printf("请输入第%d个节点的值:", i + 1);
scanf("%d", &num);
p = (Node*)malloc(sizeof(Node));
p->data = num;
p->next = NULL;
if (head == NULL) {
head = p;
} else {
q->next = p;
}
q = p;
}
return head;
}
// 合并两个有序链表
Node* merge_list(Node *head1, Node *head2) {
Node *p = head1, *q = head2, *head = NULL, *r = NULL;
// 找到头节点
if (p->data < q->data) {
head = p;
p = p->next;
} else {
head = q;
q = q->next;
}
r = head;
// 比较两个链表的节点
while (p != NULL && q != NULL) {
if (p->data < q->data) {
r->next = p;
p = p->next;
} else {
r->next = q;
q = q->next;
}
r = r->next;
}
// 处理剩余节点
if (p != NULL) {
r->next = p;
} else {
r->next = q;
}
return head;
}
// 打印链表
void print_list(Node *head) {
Node *p = head;
while (p != NULL) {
printf("%d ", p->data);
p = p->next;
}
printf("\n");
}
int main() {
int n1, n2;
Node *head1 = NULL, *head2 = NULL, *head = NULL;
printf("请输入第一个链表的长度:");
scanf("%d", &n1);
head1 = create_list(n1);
printf("请输入第二个链表的长度:");
scanf("%d", &n2);
head2 = create_list(n2);
head = merge_list(head1, head2);
printf("合并后的链表为:");
print_list(head);
return 0;
}
```
阅读全文