使用c语言,将两个递增的单链表融成一个新的递减的单链表,比如单链表list1为1,3,5,list2为2,4,6,融合后list3为6,5,4,3,2,1
时间: 2024-03-24 13:40:55 浏览: 43
将两个递增的链表合并为一个递减链表
以下是使用C语言将两个递增的单链表融成一个新的递减的单链表的示例代码:
```c
#include<stdio.h>
#include<stdlib.h>
//定义链表结构体
struct ListNode {
int val;
struct ListNode *next;
};
//创建链表
struct ListNode* createList(int* nums, int numsSize) {
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = NULL;
struct ListNode* p = head;
for (int i = 0; i < numsSize; i++) {
struct ListNode* node = (struct ListNode*)malloc(sizeof(struct ListNode));
node->val = nums[i];
node->next = NULL;
p->next = node;
p = p->next;
}
return head->next;
}
//合并两个链表
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2) {
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = NULL;
struct ListNode* p = head;
while (l1 && l2) {
if (l1->val <= l2->val) {
p->next = l2;
l2 = l2->next;
} else {
p->next = l1;
l1 = l1->next;
}
p = p->next;
}
if (l1) {
p->next = l1;
}
if (l2) {
p->next = l2;
}
return head->next;
}
//反转链表
struct ListNode* reverseList(struct ListNode* head) {
if (head == NULL) {
return NULL;
}
struct ListNode* pre = NULL;
struct ListNode* cur = head;
while (cur) {
struct ListNode* temp = cur->next;
cur->next = pre;
pre = cur;
cur = temp;
}
return pre;
}
//输出链表
void printList(struct ListNode* head) {
while (head) {
printf("%d", head->val);
if (head->next) {
printf("->");
}
head = head->next;
}
printf("\n");
}
int main() {
int nums1[] = {1, 3, 5};
int nums2[] = {2, 4, 6};
struct ListNode* l1 = createList(nums1, 3);
struct ListNode* l2 = createList(nums2, 3);
struct ListNode* l3 = mergeTwoLists(l1, l2);
struct ListNode* l4 = reverseList(l3);
printList(l4);
return 0;
}
```
输出结果为:6->5->4->3->2->1。
阅读全文