用c语言实现将两个非递减链表合成一个递减链表
时间: 2023-07-11 11:19:00 浏览: 49
可以按照以下步骤实现:
1. 定义两个链表的指针,分别指向两个非递减链表的头结点。
2. 定义一个新链表的指针,初始值为 NULL。
3. 循环比较两个链表的头结点的值,将较小的值插入到新链表的头部,并将指向该节点的指针后移。
4. 重复步骤 3 直到两个链表中有一个为空。
5. 将剩余的链表连接到新链表的尾部。
6. 返回新链表的头指针。
以下是示例代码:
```c
#include <stdio.h>
#include <stdlib.h>
struct node {
int val;
struct node* next;
};
struct node* merge_lists(struct node* l1, struct node* l2) {
struct node* new_head = NULL;
struct node** p = &new_head;
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
*p = l1;
l1 = l1->next;
} else {
*p = l2;
l2 = l2->next;
}
p = &((*p)->next);
}
if (l1 != NULL) {
*p = l1;
} else {
*p = l2;
}
struct node* prev = NULL;
struct node* curr = new_head;
while (curr != NULL) {
struct node* next = curr->next;
curr->next = prev;
prev = curr;
curr = next;
}
return prev;
}
int main() {
struct node* l1 = (struct node*)malloc(sizeof(struct node));
struct node* l2 = (struct node*)malloc(sizeof(struct node));
struct node* p1 = l1;
struct node* p2 = l2;
// 构造两个非递减链表
for (int i = 1; i <= 5; i++) {
p1->val = i;
p1->next = (struct node*)malloc(sizeof(struct node));
p1 = p1->next;
p2->val = i + 5;
p2->next = (struct node*)malloc(sizeof(struct node));
p2 = p2->next;
}
p1->next = NULL;
p2->next = NULL;
struct node* merged_list = merge_lists(l1, l2);
// 输出合并后的递减链表
while (merged_list != NULL) {
printf("%d ", merged_list->val);
merged_list = merged_list->next;
}
return 0;
}
```