C语言单链表有序表合并的代码
时间: 2023-06-03 15:02:18 浏览: 107
以下是C语言单链表有序表合并的代码:
```
#include<stdio.h>
#include<stdlib.h>
typedef struct node{
int data;
struct node* next;
}Node;
Node* CreateListNode(int data){
Node* pNew = (Node*)malloc(sizeof(Node));
if (pNew == NULL){
printf("Error: out of memory!\n");
exit(1);
}
pNew->data = data;
pNew->next = NULL;
return pNew;
}
void PrintList(Node* head){
Node* pNode = head;
if (pNode == NULL){
printf("Error: empty list!\n");
return;
}
while (pNode != NULL){
printf("%d ", pNode->data);
pNode = pNode->next;
}
printf("\n");
}
Node* MergeSortedList(Node* head1, Node* head2){
if (head1 == NULL)
return head2;
else if (head2 == NULL)
return head1;
Node* pMerge = NULL;
if (head1->data < head2->data){
pMerge = head1;
pMerge->next = MergeSortedList(head1->next, head2);
}
else{
pMerge = head2;
pMerge->next = MergeSortedList(head1, head2->next);
}
return pMerge;
}
int main(){
int data1[] = {1, 3, 4, 6, 8};
int data2[] = {-2, 0, 2, 3, 5, 7, 9};
int len1 = sizeof(data1)/sizeof(data1[0]);
int len2 = sizeof(data2)/sizeof(data2[0]);
Node* head1 = CreateListNode(data1[0]);
Node* head2 = CreateListNode(data2[0]);
Node* pNode = head1;
for (int i=1; i<len1; ++i){
pNode->next = CreateListNode(data1[i]);
pNode = pNode->next;
}
pNode = head2;
for (int i=1; i<len2; ++i){
pNode->next = CreateListNode(data2[i]);
pNode = pNode->next;
}
printf("List1: ");
PrintList(head1);
printf("List2: ");
PrintList(head2);
Node* mergedHead = MergeSortedList(head1, head2);
printf("Merged list: ");
PrintList(mergedHead);
return 0;
}
```
这段代码可以实现两个有序单链表的合并,时间复杂度为O(m+n),其中m和n分别是两个链表的长度。
阅读全文