两个有序线性表归并为一个有序线性表,使用线性表的链式存储结构表示用c语言实现
时间: 2024-03-07 09:19:25 浏览: 76
以下是使用链表实现归并排序的代码:
```c
#include <stdio.h>
#include <stdlib.h>
// 定义链表节点结构体
typedef struct Node {
int data;
struct Node *next;
} Node;
// 创建新节点
Node *createNode(int data) {
Node *node = (Node*)malloc(sizeof(Node));
node->data = data;
node->next = NULL;
return node;
}
// 合并两个有序链表
Node *merge(Node *list1, Node *list2) {
if (list1 == NULL) {
return list2;
}
if (list2 == NULL) {
return list1;
}
Node *head, *tail;
if (list1->data < list2->data) {
head = tail = list1;
list1 = list1->next;
} else {
head = tail = list2;
list2 = list2->next;
}
while (list1 != NULL && list2 != NULL) {
if (list1->data < list2->data) {
tail->next = list1;
list1 = list1->next;
} else {
tail->next = list2;
list2 = list2->next;
}
tail = tail->next;
}
if (list1 != NULL) {
tail->next = list1;
}
if (list2 != NULL) {
tail->next = list2;
}
return head;
}
// 打印链表
void printList(Node *list) {
while (list != NULL) {
printf("%d ", list->data);
list = list->next;
}
printf("\n");
}
int main() {
// 创建有序链表1
Node *list1 = createNode(1);
list1->next = createNode(3);
list1->next->next = createNode(5);
list1->next->next->next = createNode(7);
list1->next->next->next->next = createNode(9);
printf("List1: ");
printList(list1);
// 创建有序链表2
Node *list2 = createNode(2);
list2->next = createNode(4);
list2->next->next = createNode(6);
list2->next->next->next = createNode(8);
list2->next->next->next->next = createNode(10);
printf("List2: ");
printList(list2);
// 合并两个有序链表
Node *mergedList = merge(list1, list2);
printf("Merged List: ");
printList(mergedList);
return 0;
}
```
输出结果:
```
List1: 1 3 5 7 9
List2: 2 4 6 8 10
Merged List: 1 2 3 4 5 6 7 8 9 10
```
阅读全文