请用c语言编程实现有序链表合并。
时间: 2023-12-16 16:03:06 浏览: 88
好的,以下是有序链表合并的C语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int data;
struct node* next;
};
struct node* merge(struct node* list1, struct node* list2) {
struct node* result = NULL;
struct node** tail = &result;
while (1) {
if (list1 == NULL) {
*tail = list2;
break;
} else if (list2 == NULL) {
*tail = list1;
break;
}
if (list1->data <= list2->data) {
*tail = list1;
list1 = list1->next;
} else {
*tail = list2;
list2 = list2->next;
}
tail = &((*tail)->next);
}
return result;
}
void printList(struct node* list) {
while (list) {
printf("%d ", list->data);
list = list->next;
}
printf("\n");
}
int main() {
struct node* list1 = NULL;
struct node* list2 = NULL;
list1 = (struct node*)malloc(sizeof(struct node));
list1->data = 1;
list1->next = (struct node*)malloc(sizeof(struct node));
list1->next->data = 3;
list1->next->next = (struct node*)malloc(sizeof(struct node));
list1->next->next->data = 5;
list1->next->next->next = NULL;
list2 = (struct node*)malloc(sizeof(struct node));
list2->data = 2;
list2->next = (struct node*)malloc(sizeof(struct node));
list2->next->data = 4;
list2->next->next = (struct node*)malloc(sizeof(struct node));
list2->next->next->data = 6;
list2->next->next->next = NULL;
printf("List 1: ");
printList(list1);
printf("List 2: ");
printList(list2);
struct node* mergedList = merge(list1, list2);
printf("Merged list: ");
printList(mergedList);
return 0;
}
```
这里我使用了指针来操作链表,对于两个有序链表 `list1` 和 `list2`,我首先定义一个指向结果链表的指针 `tail`,然后使用循环比较 `list1` 和 `list2` 中的节点值大小,将较小的节点移动到 `tail` 指向的链表中,并更新 `tail` 指向较小值的节点。重复这个过程直到有一个链表被遍历完,最后将 `tail` 指向另一个链表的剩余部分,即得到了合并后的有序链表。
希望这段代码能帮到您!
阅读全文