我想用c语言把两个升序排列的链表合成一个降序排列的链表
时间: 2023-03-28 14:02:16 浏览: 127
好的,这是一个关于编程的问题。可以使用归并排序的思想,将两个升序排列的链表合并成一个降序排列的链表。具体实现可以参考以下代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
if (l1 == NULL) {
return l2;
}
if (l2 == NULL) {
return l1;
}
if (l1->val < l2->val) {
l1->next = mergeTwoLists(l1->next, l2);
return l1;
} else {
l2->next = mergeTwoLists(l1, l2->next);
return l2;
}
}
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr != NULL) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
ListNode* mergeSortedList(ListNode* l1, ListNode* l2) {
ListNode* mergedList = mergeTwoLists(l1, l2);
ListNode* reversedList = reverseList(mergedList);
return reversedList;
}
int main() {
// 创建两个升序排列的链表
ListNode* l1 = (ListNode*)malloc(sizeof(ListNode));
l1->val = 1;
l1->next = (ListNode*)malloc(sizeof(ListNode));
l1->next->val = 3;
l1->next->next = (ListNode*)malloc(sizeof(ListNode));
l1->next->next->val = 5;
l1->next->next->next = NULL;
ListNode* l2 = (ListNode*)malloc(sizeof(ListNode));
l2->val = 2;
l2->next = (ListNode*)malloc(sizeof(ListNode));
l2->next->val = 4;
l2->next->next = (ListNode*)malloc(sizeof(ListNode));
l2->next->next->val = 6;
l2->next->next->next = NULL;
// 合并两个升序排列的链表为一个降序排列的链表
ListNode* mergedList = mergeSortedList(l1, l2);
// 打印结果
ListNode* curr = mergedList;
while (curr != NULL) {
printf("%d ", curr->val);
curr = curr->next;
}
printf("\n");
return ;
}
```
阅读全文