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