假设有两个按元素值递增次序排列的线性表均以单链表形式存储。请用c语言编写算法将这两个单链表归并为一个按元素值递增次序排列的单链表,并要求利用原来两个单链表的结点存放归并后的单链表。
时间: 2023-05-11 17:05:31 浏览: 150
以下是C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode *next;
} ListNode;
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode *dummy = (ListNode *)malloc(sizeof(ListNode));
ListNode *cur = dummy;
while (l1 && l2) {
if (l1->val < l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return dummy->next;
}
int main() {
ListNode *l1 = (ListNode *)malloc(sizeof(ListNode));
l1->val = 1;
l1->next = (ListNode *)malloc(sizeof(ListNode));
l1->next->val = 3;
l1->next->next = (ListNode *)malloc(sizeof(ListNode));
l1->next->next->val = 5;
l1->next->next->next = NULL;
ListNode *l2 = (ListNode *)malloc(sizeof(ListNode));
l2->val = 2;
l2->next = (ListNode *)malloc(sizeof(ListNode));
l2->next->val = 4;
l2->next->next = (ListNode *)malloc(sizeof(ListNode));
l2->next->next->val = 6;
l2->next->next->next = NULL;
ListNode *merged = mergeTwoLists(l1, l2);
while (merged) {
printf("%d ", merged->val);
merged = merged->next;
}
printf("\n");
return 0;
}
```
这个算法的时间复杂度是O(m+n),其中m和n分别是两个单链表的长度。
阅读全文