用c语言写一个两个无序链表的合并,成有序链表的代码
时间: 2023-03-31 22:04:39 浏览: 131
多项式相加(C语言-链表版+数组版).zip
可以使用归并排序的思想,将两个无序链表合并成一个有序链表。具体实现可以参考以下代码:
```
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int val;
struct Node *next;
} Node;
Node *merge(Node *head1, Node *head2) {
if (!head1) return head2;
if (!head2) return head1;
Node *dummy = (Node *)malloc(sizeof(Node));
Node *tail = dummy;
while (head1 && head2) {
if (head1->val < head2->val) {
tail->next = head1;
head1 = head1->next;
} else {
tail->next = head2;
head2 = head2->next;
}
tail = tail->next;
}
if (head1) tail->next = head1;
if (head2) tail->next = head2;
return dummy->next;
}
int main() {
Node *head1 = (Node *)malloc(sizeof(Node));
Node *head2 = (Node *)malloc(sizeof(Node));
head1->val = 1;
head1->next = (Node *)malloc(sizeof(Node));
head1->next->val = 3;
head1->next->next = (Node *)malloc(sizeof(Node));
head1->next->next->val = 5;
head1->next->next->next = NULL;
head2->val = 2;
head2->next = (Node *)malloc(sizeof(Node));
head2->next->val = 4;
head2->next->next = (Node *)malloc(sizeof(Node));
head2->next->next->val = 6;
head2->next->next->next = NULL;
Node *merged = merge(head1, head2);
while (merged) {
printf("%d ", merged->val);
merged = merged->next;
}
return ;
}
```
阅读全文