将两个非递减单链表合并成一个有序的非递减单链表的c语言代码
时间: 2024-03-24 14:14:49 浏览: 83
合并两链表成有序表 VC++ 代码
下面是将两个非递减单链表合并成一个有序的非递减单链表的c语言代码:
```c
#include <stdio.h>
#include <stdlib.h>
typedef struct ListNode {
int val;
struct ListNode* next;
} ListNode;
ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
ListNode* head = (ListNode*)malloc(sizeof(ListNode));
ListNode* cur = head;
while (l1 != NULL && l2 != NULL) {
if (l1->val <= l2->val) {
cur->next = l1;
l1 = l1->next;
} else {
cur->next = l2;
l2 = l2->next;
}
cur = cur->next;
}
if (l1 != NULL) {
cur->next = l1;
}
if (l2 != NULL) {
cur->next = l2;
}
return head->next;
}
int main() {
// test case
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 = mergeTwoLists(l1, l2);
while (mergedList != NULL) {
printf("%d ", mergedList->val);
mergedList = mergedList->next;
}
return 0;
}
```
这段代码可以将两个非递减单链表合并成一个有序的非递减单链表。具体实现是先创建一个空的头结点,然后遍历两个链表,每次将较小的节点加入到新链表中即可。最后需要注意的是,返回结果应该是头结点的下一个节点。
阅读全文