用C代码实现将两个递增的有序链表合并为一个递增的有序链表
时间: 2023-10-18 20:07:11 浏览: 96
```c
#include <stdio.h>
#include <stdlib.h>
struct Node {
int data;
struct Node* next;
};
struct Node* createNode(int data) {
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
struct Node* mergeLists(struct Node* list1, struct Node* list2) {
struct Node* mergedList = createNode(0);
struct Node* tail = mergedList;
while (1) {
if (list1 == NULL) {
tail->next = list2;
break;
}
else if (list2 == NULL) {
tail->next = list1;
break;
}
if (list1->data <= list2->data) {
tail->next = list1;
list1 = list1->next;
}
else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
return mergedList->next;
}
void printList(struct Node* node) {
while (node != NULL) {
printf("%d ", node->data);
node = node->next;
}
printf("\n");
}
int main() {
struct Node* list1 = createNode(1);
list1->next = createNode(3);
list1->next->next = createNode(5);
list1->next->next->next = createNode(7);
struct Node* list2 = createNode(2);
list2->next = createNode(4);
list2->next->next = createNode(6);
list2->next->next->next = createNode(8);
printf("List 1: ");
printList(list1);
printf("List 2: ");
printList(list2);
struct Node* mergedList = mergeLists(list1, list2);
printf("Merged List: ");
printList(mergedList);
return 0;
}
```
输出:
```
List 1: 1 3 5 7
List 2: 2 4 6 8
Merged List: 1 2 3 4 5 6 7 8
```
阅读全文