21. 合并两个有序链表
题目:
将两个升序链表合并为一个新的 升序 链表并返回。新链表是通过拼接给定的两个链表的所有节点组成的。
示例:
输入:1->2->4, 1->3->4 输出:1->1->2->3->4->4
思路:
用两个指针指向分别指向两个链表,比较指针指向的两个节点,小的那个指针往后移,并且把小的那个节点添加到合并后的新链表中。
dummy node:如果新链表不用dummy node记录首节点,随着添加节点,首节点会不断向后移动,无法返回这个链表了。
深拷贝:java中,对象的 = 赋值,是两个引用指向相同的空间。
时间复杂度:遍历两个链表,O(m+n)
空间复杂度:不知道新链表的长度, O(m+n)
代码:
public class mergeTwoLists_21 {
public static ListNode mergeTwoLists(ListNode l1, ListNode l2) {
if (l1 == null) return l2;
if (l2 == null) return l1;
ListNode dummy = new ListNode();
ListNode head = dummy;
while (l1 != null && l2 != null) {
if (l1.val < l2.val) {
head.next = l1;
l1 = l1.next;
head = head.next;
} else {
head.next = l2;
l2 = l2.next;
head = head.next;
}
}
head.next = l1 == null ? l2 : l1;
return dummy.next;
}
}