将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例 1:
输入:l1 = [1,2,4], l2 = [1,3,4] 输出:[1,1,2,3,4,4]
示例 2:
输入:l1 = [], l2 = [] 输出:[]
示例 3:
输入:l1 = [], l2 = [0] 输出:[0]
class Solution {
public:
ListNode* mergeTwoLists(ListNode* head1, ListNode* head2) {
if(head1 == NULL || head2 == NULL) return head1 == NULL ? head2 : head1;
ListNode* head = head1->val <= head2->val ? head1:head2;
ListNode* cur1 = head->next;
ListNode* cur2 = head == head1 ? head2 : head1;
ListNode* pre = head;
while(cur1 != NULL && cur2 != NULL) {
if(cur1->val <= cur2->val) {
pre->next = cur1;
cur1 = cur1->next;
} else {
pre->next = cur2;
cur2 = cur2->next;
}
pre = pre->next;
}
pre->next = cur1 != NULL ? cur1:cur2;
return head;
}
};