思路:
处理特殊情况(均为空、某个为空);
循环合并,仅改变cur指针的next地址;
处理尾部,由于存在某条链表先被遍历完的情况,所以在最后要做特殊处理
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
//排除特殊情况
if(l1 == null && l2 == null) return l1;
if(l1 != null && l2 == null) return l1;
if(l1 == null && l2 != null) return l2;
//两个链表均有结点时
ListNode head = new 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;
}
//如果有条链表先遍历完了怎么办?
cur.next = l1 == null ? l2 : l1;
return head.next;
}
}