7-51 两个有序链表序列的合并使用C语言实现
时间: 2024-04-29 08:22:24 浏览: 13
以下是使用C语言实现合并两个有序链表序列的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表结构体
typedef struct Node {
int value; // 值
struct Node *next; // 指向下一个节点的指针
} Node;
// 合并两个有序链表
Node *mergeLists(Node *list1, Node *list2) {
Node *head = NULL; // 合并后链表的头节点
Node *tail = NULL; // 合并后链表的尾节点
// 如果有一个链表为空,则直接返回另一个链表
if (list1 == NULL) {
return list2;
} else if (list2 == NULL) {
return list1;
}
// 选择头节点
if (list1->value < list2->value) {
head = list1;
list1 = list1->next;
} else {
head = list2;
list2 = list2->next;
}
tail = head;
// 循环合并两个链表
while (list1 != NULL && list2 != NULL) {
if (list1->value < list2->value) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
// 将剩余的节点添加到尾部
if (list1 != NULL) {
tail->next = list1;
} else {
tail->next = list2;
}
return head;
}
// 打印链表
void printList(Node *list) {
while (list != NULL) {
printf("%d ", list->value);
list = list->next;
}
printf("\n");
}
int main() {
// 创建两个有序链表
Node *list1 = (Node *) malloc(sizeof(Node));
list1->value = 1;
list1->next = (Node *) malloc(sizeof(Node));
list1->next->value = 3;
list1->next->next = (Node *) malloc(sizeof(Node));
list1->next->next->value = 5;
list1->next->next->next = NULL;
Node *list2 = (Node *) malloc(sizeof(Node));
list2->value = 2;
list2->next = (Node *) malloc(sizeof(Node));
list2->next->value = 4;
list2->next->next = (Node *) malloc(sizeof(Node));
list2->next->next->value = 6;
list2->next->next->next = NULL;
// 合并两个有序链表
Node *mergedList = mergeLists(list1, list2);
// 打印合并后的链表
printList(mergedList);
return 0;
}
```
输出结果为:
```
1 2 3 4 5 6
```