#include
#include
// 定义链表节点结构
struct Node {
int data;
struct Node *next;
};
// 插入节点到链表头部
void insertNode(struct Node **head, int data) {
struct Node *newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = *head;
*head = newNode;
}
// 合并两个有序链表
struct Node* mergeLists(struct Node *list1, struct Node *list2) {
struct Node dummyNode;
struct Node *tail = &dummyNode;
dummyNode.next = NULL;
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;
} else {
tail->next = list2;
}
return dummyNode.next;
}
// 反转链表
void reverseList(struct Node **head) {
struct Node *prev = NULL;
struct Node *current = *head;
struct Node *next = NULL;
while (current != NULL) {
next = current->next;
current->next = prev;
prev = current;
current = next;
}
*head = prev;
}
// 打印链表
void printList(struct Node *head) {
struct Node *current = head;
while (current != NULL) {
printf("%d ", current->data);
current = current->next;
}
printf("\n");
}
int main() {
struct Node *list1 = NULL;
struct Node *list2 = NULL;
// 创建第一个有序链表
insertNode(&list1, 5);
insertNode(&list1, 3);
insertNode(&list1, 1);
// 创建第二个有序链表
insertNode(&list2, 6);
insertNode(&list2, 4);
insertNode(&list2, 2);
printf("List 1: ");
printList(list1);
printf("List 2: ");
printList(list2);
// 合并两个有序链表
struct Node *mergedList = mergeLists(list1, list2);
// 反转链表,使元素值递减排列
reverseList(&mergedList);
printf("Merged List: ");
printList(mergedList);
return 0;
}
这个算法的基本思路是,首先定义一个虚拟节点作为新链表的头部,然后比较两个链表的当前节点值,将较小的节点插入到新链表的尾部,然后更新相应的指针。最后,将新链表反转,使元素值递减排列。在示例代码中,我们创建了两个有序链表,然后调用 mergeLists
函数将它们合并,并通过 reverseList
函数将结果链表反转。最后,打印出合并后的链表。