给定两个链表,每个链表都已经按升序排列,设计算法实现将两个链表合并到一个升序链表中,返回合并后的链表,用c语言写出这段代码
时间: 2023-05-21 16:01:58 浏览: 68
以下是C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
struct ListNode {
int val;
struct ListNode *next;
};
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode *head = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *cur = head;
while(l1 && l2){
if(l1->val <= l2->val){
cur->next = l1;
l1 = l1->next;
}else{
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
cur->next = l1 ? l1 : l2;
return head->next;
}
int main(){
struct ListNode *l1 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *l2 = (struct ListNode*)malloc(sizeof(struct ListNode));
struct ListNode *cur1 = l1;
struct ListNode *cur2 = l2;
int arr1[3] = {1, 2, 4};
int arr2[3] = {1, 3, 4};
for(int i = 0; i < 3; i++){
cur1->val = arr1[i];
cur2->val = arr2[i];
if(i != 2){
cur1->next = (struct ListNode*)malloc(sizeof(struct ListNode));
cur2->next = (struct ListNode*)malloc(sizeof(struct ListNode));
cur1 = cur1->next;
cur2 = cur2->next;
}
}
cur1->next = NULL;
cur2->next = NULL;
struct ListNode *res = mergeTwoLists(l1, l2);
while(res){
printf("%d ", res->val);
res = res->next;
}
return 0;
}
```
这段代码实现了将两个升序链表合并成一个升序链表的功能。
阅读全文