一、题目
输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。
示例1:
输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
二、思路
二路归并的思想,依次从两个链表中选出最小的节点加入新的链表,终止条件为一个链表为空。最后将另外一个链表全部加入新链表中即可
三、C语言解法
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* Insert(struct ListNode* head,int val){
struct ListNode* p = (struct ListNode*)malloc(sizeof(struct ListNode));
p->val = val;
p->next = head->next;
head->next = p;
return p;
}
struct ListNode* mergeTwoLists(struct ListNode* l1, struct ListNode* l2){
struct ListNode* head = (struct ListNode*)malloc(sizeof(struct ListNode));
head->next = NULL;
struct ListNode* tail = head;
while(l1!=NULL&&l2!=NULL){
if(l2->val>l1->val) {
tail = Insert(tail,l1->val);
l1 = l1->next;
}
else{
tail = Insert(tail,l2->val);
l2 = l2->next;
}
}
while(l1!=NULL) {tail = Insert(tail,l1->val);l1 = l1->next;}
while(l2!=NULL) {tail = Insert(tail,l2->val);l2 = l2->next;}
return head->next;
}