用C语言编写一串代码,将两个升序的头指针型单链表合并为降序的头指针单链表
时间: 2023-05-27 21:03:02 浏览: 100
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
ListNode* merge(ListNode* l1, ListNode* l2) {
ListNode preHead = {0, NULL};
ListNode* tail = &preHead;
while (l1 && l2) {
if (l1->val < l2->val) {
tail->next = l1;
l1 = l1->next;
} else {
tail->next = l2;
l2 = l2->next;
}
tail = tail->next;
}
tail->next = l1 ? l1 : l2;
return preHead.next;
}
ListNode* reverseList(ListNode* head) {
ListNode* prev = NULL;
ListNode* curr = head;
while (curr) {
ListNode* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
ListNode* l1 = (ListNode*)malloc(sizeof(ListNode));
ListNode* l2 = (ListNode*)malloc(sizeof(ListNode));
l1->val = 1;
l2->val = 2;
l1->next = l2->next = NULL;
ListNode* merged = merge(l1, l2);
ListNode* reversed = reverseList(merged);
return 0;
}
```
注意:这里的`merge`函数是直接从leetcode上拷贝过来的,因为其实现简单而且没有问题。`reverseList`函数是一个简单的单链表反转操作。
我们先创建两个升序单链表,然后调用`merge`函数将其合并为升序(`merge`函数的实现中将大的放在前面),最后调用`reverseList`函数将链表反转,就可以得到降序的单链表。
阅读全文