https://leetcode-cn.com/problems/merge-two-sorted-lists/
方法一:迭代
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode() {}
* ListNode(int val) { this.val = val; }
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
* }
*/
class Solution {
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if(l1==null&&l2==null)
return null;
if(l1==null)
return l2;
if(l2==null)
return l1;
ListNode head=new ListNode();
ListNode tmp=head;
while(l1!=null&&l2!=null){
if(l1.val<=l2.val){
head.next=l1;
l1=l1.next;
}
else{
head.next=l2;
l2=l2.next;
}
head=head.next;
}
if(l1!=null)
head.next=l1;
if(l2!=null)
head.next=l2;
return tmp.next;
}
}
时间复杂度:O(n+m) ,其中 n 和 m 分别为两个链表的长度。因为每次循环迭代中,l1 和 l2 只有一个元素会被放进合并链表中, 因此 while 循环的次数不会超过两个链表的长度之和。所有其他操作的时间复杂度都是常数级别的,因此总的时间复杂度为 O(n+m)。
空间复杂度:O(1) 。我们只需要常数的空间存放若干变量。