【力扣】剑指 Offer 25. 合并两个排序的链表
阅读原文时间:2023年07月08日阅读:1

输入两个递增排序的链表,合并这两个链表并使新链表中的节点仍然是递增排序的。

示例1:

输入:1->2->4, 1->3->4
输出:1->1->2->3->4->4
限制:

0 <= 链表长度 <= 1000

来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/he-bing-liang-ge-pai-xu-de-lian-biao-lcof
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode head = null;
ListNode current = new ListNode(0);
while(l1 != null || l2 != null){
//判断l1 和 l2哪个大
if(l1 != null && l2 != null){
if(l1.val >= l2.val){
current.next = new ListNode(l2.val);
l2 = l2.next;
} else {
current.next = new ListNode(l1.val);
l1 = l1.next;
}
} else if(l1 == null){
current.next = new ListNode(l2.val);
l2 = l2.next;
} else {
current.next = new ListNode(l1.val);
l1 = l1.next;
}
if(head == null){
head = current;
}
current = current.next;
}
if(head == null){
return null;
}
return head.next;
}

//时间复杂度O(n)  
//空间复杂度O(1) 只用了两个指针,结果不计算在内